如何在 nginx 中将 www 重定向到非 www
How to redirect www to non-www in nginx
这是我当前的 nginx 配置:
server {
server_name mydomain.com www.mydomain.com;
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
if ($host = www.mydomain.com) {
return 301 https://$host$request_uri;
}
if ($host = mydomain.com) {
return 301 https://$host$return_uri;
}
server_name mydomain.com www.mydomain.com
listen 80;
return 404;
}
这很好用,但我也需要将 www
重定向到 non-www
。怎么做?
试试这个:
location / {
if ($http_host ~* "^www.example.com"){
rewrite ^(.*)$ https://example.com/ redirect;
}
}
这是我当前的 nginx 配置:
server {
server_name mydomain.com www.mydomain.com;
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
if ($host = www.mydomain.com) {
return 301 https://$host$request_uri;
}
if ($host = mydomain.com) {
return 301 https://$host$return_uri;
}
server_name mydomain.com www.mydomain.com
listen 80;
return 404;
}
这很好用,但我也需要将 www
重定向到 non-www
。怎么做?
试试这个:
location / {
if ($http_host ~* "^www.example.com"){
rewrite ^(.*)$ https://example.com/ redirect;
}
}