"Nginx"-Redirect HTTP to HTTPS link @20210228

Problem Description

Since the large-scale use of HTTPS, all HTTP access has to be redirected to HTTPS sites. Otherwise, the customer will only enter the domain name, and many browsers use the HTTP protocol by default. If we do not provide HTTP access and do not redirect, the customer will see a blank page (unavailable), and the customer will think that our site has The problem, after all, where does the customer know what HTTP is and what is HTTPS.

Therefore, we need to redirect HTTP requests to HTTPS sites. Of course, this kind of redirection is generally for GET requests, and it is not necessary to be complicated to redirect HTTP Post requests to HTTPS Post requests, so we did not discuss these issues, and we will talk about them later.

This note will record: How to redirect HTTP requests to HTTPS requests in Nginx, and write common and convenient practices.

solution

Plan one, conventional plan

The conventional solution is to add redirects for each site, and the configuration is roughly the following structure:

server {
    listen 80;
    server_name http.example.com;
    rewrite ^(.*) https://$server_name$1 permanent;
}

server {
    server_name https.example.com;
    listen 443 ssl;
    
    ssl_certificate /path/to/pem;
    ssl_certificate_key /path/to/key;
    
    location / {}
}

However, the biggest problem with this method is: to add HTTP redirects for each domain name (such as the configuration of the first server {}), is there any way to "get it all right once and for all"? That must have:

Solution two, handle all HTTP redirects

Through the following configuration, there is no need to add HTTP configuration for the domain name in the future.

server {
    listen 80 default_server;

    server_name _;

    return 301 https://$host$request_uri;
}

Explanation: Due to the existence of default_server, those unconfigured HTTP domain names will match the server {} block, and then return 301 will be redirected to the corresponding HTTPS site.

references

Module ngx_http_rewrite_module
rewrite - What is the difference between Nginx variables $host, $http_host, and $server_name? - Server Fault
Redirect HTTP to HTTPS in Nginx | Servers for Hackers

Guess you like

Origin blog.csdn.net/u013670453/article/details/114207947