雪花臺灣

我的 Nginx 配置,域名不帶 www 跳轉到www,http 強制跳轉 https,這些都有了

話不多說,先貼部分配置:

server {
listen 80;
server_name www.your-domain.com;
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
}
server {
listen 443 ssl;
server_name www.your-domain.com;

ssl_certificate /home/ssl_certificate/your-domain.com.pem;
ssl_certificate_key /home/ssl_certificate/your-domain.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_session_timeout 5m;

if ( $host != www.your-domain.com ) {
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
}

root /var/www/html;

index index.html index.htm index.nginx-debian.html;

# server_name _;

location / {
proxy_pass http://127.0.0.1:8080;
}
}

一、https 配置

server {
# 我們都知道(我們都應該知道),443是 https 的默認埠
listen 443 ssl;
server_name www.your-domain.com;
# 你要有證書,才能 https,免費申請一個吧,七牛雲,阿里雲都有免費一年的證書
ssl_certificate /home/ssl_certificate/your-domain.com.pem;
ssl_certificate_key /home/ssl_certificate/your-domain.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_session_timeout 5m;
# 下面這句就是當識別到 HOST 不是帶 www 的全部都 301 帶上 www
if ( $host != www.your-domain.com ) {
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
}

root /var/www/html;

index index.html index.htm index.nginx-debian.html;

# server_name _;

location / {
# 我是 java web 所以用了 Tomcat ,但是我要用 nginx 做轉發,因此有了如下的配置
proxy_pass http://127.0.0.1:8080;
}
}

二、將http強製為https訪問

80443 埠分別配置一個 server,讓80 埠訪問的強制 301 跳轉到 https。如下所示:

把所攜帶的參數都帶上
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
}

三、將不帶www的訪問強制加上www

nginx 的配置文件可以寫這種判斷和表達式,總之是很厲害的,仔細觀察下面的 if 判斷很容易明白講的什麼意思,當 HOST 不是帶 www 的訪問時 302 到 www 上面。

# 下面這句就是當識別到 HOST 不是帶 www 的全部都 302 帶上 www
if ( $host != www.your-domain.com ) {
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
}

需要注意的是:if ( $host != www.your-domain.com ) { 這一句一定要按照格式書寫,括弧前後的空格必須帶著,還有if之後的空格也一樣。如果不!會報錯:

unknown directive "if($host!="

四、總結一下

(寫著,寫著,變成怎麼做一個好站長了。)

推薦閱讀:

查看原文 >>
相關文章