知識庫

在 Nginx Web 伺服器上設定 HTTPS 重新導向

When an SSL certificate is installed, and the site can be accessed via https:// scheme, it is the right time to enable an automatic redirect so that one gets to https://example.com or https://www.example.com every time when http://example.com or http://www.example.com is requested.

According to Nginx reference materials on the matter like this one, there are several directives which can be used for accomplishing our goal. We will use the 'return' directive as the simplest and the most effective one from the point of impact on web-server performance.

Redirecting a specific site

To redirect a specific site to https://, it is necessary to open the configuration file with a server block (virtual host) for port 80 (it can be either the main nginx.conf or another configuration file with the server block specifically) and add the following line inside the block:

return 301 https://www.example.com$request_uri;

Ngxred1

Default redirect for all sites

It is possible to set up a redirect rule, which is applied for every site, configured on a given Nginx web-server instance. We need to modify the server block, which is used as a default one for accessing the server. The redirect directive needs to be set with the 'server_name' variable instead of the specific domain name:

return 301 https://$server_name$request_uri;

Ngxred2

Enabling HTTPS redirect for a specific directory

If we need only the content from a specific folder to be served over https://, we can use the 'location' directive for that:

location ^~ /test {
return 301 https://example.com$request_uri;
}

This rule defines that the redirect is applied only for the files located inside the 'test' directory and the directory itself. It is also possible to redirect several folders by creating corresponding 'location' blocks for each of them.

Ngxred3

Redirecting a specific page

Using the same 'location' directive, we can force HTTPS connection for specific pages and files. The redirect rule will be displayed in a following way:

location ^~ /test.txt {
return 301 https://example.com$request_uri;
}

Ngxred4

We have covered several common use cases of setting HTTPS redirect on Nginx using the 'return' directive. The provided rulesets are aimed to show basic configuration options. Feel free to combine or modify them according to your requirements referring to Nginx documentation on this topic.