1 頁 (共 1 頁)

Nginx - Redirect to HTTPS with/without www subdomain

發表於 : 2016-07-16 17:43:21
yehlu
https://bashy.im/blog/nginx-redirect-to ... -subdomain

Nginx HTTP to HTTPS and vice versa (IPv4 & IPv6)

I run sites from /etc/nginx/sites-available/ and symlink them to /etc/nginx/sites-enabled/ (pretty basic setup).

Now to the code. There's a different way to do this but personally wouldn't use it, using map module.
Example of map to redirect certain folders/paths to HTTPS (although "if" is evil) can be found here



All these parts are put into file: /etc/nginx/sites-available/example.com

*Replace example.com with your domain which you use.*

This first server block is for normal port 80 (IPv4 IPv6 HTTP) traffic and it will redirect both http://www.example.com and http://example.com to https://example.com

代碼: 選擇全部

server {
        listen 80;
        listen [::]:80;

        server_name www.example.com example.com;

        return 301 https://example.com$request_uri;
}
This second block is to catch port 443 (IPv4 IPv6 HTTPS) traffic and it will redirect https://www.example.com to https://example.com

代碼: 選擇全部

server {
        listen 443 ssl;
        listen [::]:443 ssl;
        ssl_certificate /etc/nginx/certs/example.crt;
        ssl_certificate_key /etc/nginx/certs/example.key;

        # Ciphers and protocols
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Excludes SSLv2/3
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; # Current at the time of Feb 2016
        ssl_prefer_server_ciphers on;

        server_name www.example.com;

        return 301 https://example.com$request_uri;
}
This last block will act as your main setup. Here you put all the logic in like logs, cache, PHP, rewrites etc.

代碼: 選擇全部

server {
        listen 443 ssl;
        listen [::]:443 ssl;
        ssl_certificate /etc/nginx/certs/example.crt;
        ssl_certificate_key /etc/nginx/certs/example.key;

        # Ciphers and protocols
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Excludes SSLv2/3
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; # Current at the time of Feb 2016
        ssl_prefer_server_ciphers on;

        server_name example.com;

        [...]
}