Help
Redirect http to https in NGINX server.

Redirect http to https in NGINX server.

While setting up server, you have two server blocks for the domain you are working. They are HTTP version on port 80 and HTTPS version on port 443. So, basically all request with HTTP goes to the port 80 and HTTPS goes to the port 443.

Redirect all urls to HTTPS

  • sudo nano /etc/nginx/sites-available/default
  • Copy following code and paste in your default file.
server {
	listen 80 default_server;
	listen [::]:80 default_server;
	server_name _;
	return 301 https://$host$request_uri;
}
  • control+x
  • y
  • enter or return
  • sudo /etc/init.d/nginx restart

Whenever you make changes to default file you need to restart Nginx service. sudo /etc/init.d/nginx restart does that for you. Now every request user makes in your site will redirect to https.

Redirect individual url to HTTPS

  • sudo nano /etc/nginx/sites-available/default
  • Copy following code and paste in your default file
server {
     listen 80;
     server_name santoshm.com.np www.santoshm.com.np;
     return 301 https://santoshm.com.np$request_uri;
 }
  • control+x
  • y
  • enter or return
  • sudo /etc/init.d/nginx restart

It is better to make sure each and every url in your websites are going through https rather than http. So I would recommend to use Redirecting all url to HTTPS approach.

Hope this blog was helpful. Don’t forget to share guys.

Thanks

Leave a Reply