Like most web sites that follow current trends, linuxinf.com uses the secure https communication protocol. Many sites, when switching to https, need all traffic that comes to the http port to be automatically redirected to https.
This is necessary for reasons of SEO optimization, as well as user security, so that no one can break the secure connection. In this article, we will look at how to set up a redirect from http to https Nginx.
Redirect from http to https Nginx
I’m assuming you’ll be using a permanent redirect with a 301 status code. This means moving permanently. This method is used to inform search engines or the browser that the current link has been updated and should be updated in its database, such as browser bookmarks.
There should be two server sections in the Nginx configuration file, for an https site and an http site. In the http section, you simply redirect all requests to https using the return statement, and in the second section, you process everything. For example, the first section:
The second section, already with SSL processing, listens for requests on port 443:
Actually, the syntax here is very simple, the return statement allows you to return the necessary server response codes. Here we return a 301 code, a permanent redirect, and also the URL to which we are going to redirect the user. In addition to the return directive, you can use the rewrite instruction, which performs exactly the same actions:
This is normal regular expression syntax. In the first argument, we select the query string group, and in the second argument, we specify the correct domain. You can add it instead of return 301. You can also use this construct without a separate server block:
Now it remains to test what happened. Save the file and check the nginx configuration:
sudo nginx -t
Then, if all is well, restart Nginx:
sudo systemctl restart nginx
Next, you can check what server response you will receive using curl:
curl -I linuxinf.com
Or let the utility follow the full path through the redirect:
curl ILa linuxinf.com
Findings
Setting up a redirect to https nginx is quite simple, in fact, everything is done by adding one line to the configuration file, everything else is additional parameters. A redirect from https to http nginx will work the same way. Only a few letters in the retrun parameters will need to be changed. Don’t forget to check if the www and https redirects are set up correctly, this plays a very important role for SEO. I hope this information was helpful to you.