nginx - Nginx 不会重定向到 www
问题描述
您好,我很难正确配置 nginx。我想从https://example.com重定向到https://www.example.com我发现很多教程如何做到这一点,但没有一个与我的配置文件一起使用。我使用letsencrpyt 为我配置SSL。这是 nginx 配置文件:
server {
server_name IP_ADDRESS example.com www.example.com;
location /static/ {
root /home/user/pyapps/ks_g;
}
location /media/ {
root /home/user/pyapps/ks_g;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name IP_ADDRESS example.com www.example.com;
return 404; # managed by Certbot
}
解决方案
使用 SSL 或两者都将重定向条件添加到服务器块:
if ($host != www.example.com) {
return 301 https://www.example.com$request_uri;
} # managed by Stack Overflow (sorry cannot hold myself)
其工作原理如下:如果Host
HTTP 标头不等于www.example.com
,则永久重定向到https://www.example.com$request_uri
.
推荐阅读
- excel - 如果值 > 0 错误,则将行复制并粘贴到新工作表的宏
- c# - 如何使用嵌入的单声道将字符串参数传递给 c# 方法?
- aws-iot - aws iot 如何生成证书 ID?
- selenium-webdriver - 通过 Junit 执行测试时无法生成 Serenity 汇总报告
- function - 如何从 mariadb 函数返回表?
- python - 解析 csv 文件,将行存储/写入到旧文件中的行之间的新文件
- python - 如何通过单位矩阵屏蔽 groupby 数据帧
- javascript - 如何在 NodeJS 中创建 True Singleton 而不依赖其缓存系统
- javascript - 根据另一个数组中的键更新数组数据
- reactjs - 在 redux-saga 中启动新的时如何清除之前的延迟效果