原文地址
我的 Nginx 配置,域名不带 www 跳转到www,http 强制跳转 https,这些都有了
nginx.conf
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 to https
将 80 与 443 端口分别配置一个 server,让80 端口访问的强制 301 跳转到 https。如下所示:
rewrite ^(.*)$ https://www.your-domain.com$1 permanent;
强制添加 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!="
评论补充
server {
listen 80;
server_name www.hichinese.world hichinese.world;
rewrite ^(.*)$ https://${server_name}$1 permanent;
}
server {
listen 443 ssl http2;
server_name www.hichinese.world hichinese.world;
access_log /app/log/nginx/hichinese_upstream_access.log main;
error_log /app/log/nginx/hichinese_upstream_error.log;
if ( $host != 'www.hichinese.world' ) {
rewrite ^(.*)$ https://www.hichinese.world$1 permanent;
}
}