Redirecting to SSL using nginx

前端 未结 5 1694
傲寒
傲寒 2020-12-08 16:29

I have http:// and https:// on the same host like the following:

server {

    listen   80;
    listen   443 ssl;

    ...
    ...
}

What I

相关标签:
5条回答
  • 2020-12-08 16:45

    It would also be more of an NGINX best practice to do a 301 redirect instead of using the if statement (see Server name on http://wiki.nginx.org/Pitfalls). I created a gist with an nginx.conf configured for SSL, Rails and Unicorn

    https://gist.github.com/Austio/6399964

    Here would be the relevant section for yours.

    server {
        listen      80;
        server_name domain.com;
        return 301  https://$host$request_uri;
    }
    
    0 讨论(0)
  • 2020-12-08 16:45

    Or better yet, avoiding the hardcoded server name

    server {
      listen 80;
      rewrite (.*) https://$http_host$1 permanent;
    }
    
    0 讨论(0)
  • 2020-12-08 16:52

    Ideally, avoiding if statements while preserving the trailing path:

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

    permanent takes care of the 301.

    0 讨论(0)
  • 2020-12-08 16:59

    In order to use regular expressions for matching locations, you need to prefix the expression with either ~ or ~*:

    if ($server_port = 80) {
        location ~ (en|fr)/shop {
            rewrite ^ https://$host$request_uri permanent;
        }
    }
    

    From the documentation:

    To use regular expressions, you must use a prefix:

    1. "~" for case sensitive matching
    2. "~*" for case insensitive matching

    Since nginx does't allow location blocks to be nested inside of if blocks, try the following configuration:

    if ($server_port = 80) {
        rewrite ^/(en|fr)/shop https://$host$request_uri permanent;
    }
    
    0 讨论(0)
  • 2020-12-08 16:59

    another way with error_page 497

    server {
        listen 80;
        listen 443;
    
        ssl on;
        error_page 497  https://$host$request_uri;
        ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
        ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
    ...
    
    0 讨论(0)
提交回复
热议问题