大网数据广告活动
服务器运维问答

nginx rewrite from www to non-www

· 52CE 我爱测

My nginx file doesn't file is failing and I'm not sure how. I have managed to redirect from http to https fine. But I can't get the www to redirect to non-www version. What am I doing wrong? server { listen 80; server_name exampl…

问题原文

原帖链接 · Jonnny · CC BY-SA 3.0

My nginx file doesn't file is failing and I'm not sure how. I have managed to redirect from http to https fine. But I can't get the www to redirect to non-www version. What am I doing wrong?

server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;

location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/sammy/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
}
# added for let's encrypt
location /.well-known/ {
   root /home/sammy/myproject;
   allow all;
}
}
server {
# SSL configuration

listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
include snippets/ssl-example.com.conf;
include snippets/ssl-params.conf;

    location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
    root /home/myproject/myproject;
}

location / {
    include proxy_params;
    proxy_pass http://unix:/home/sammy/myproject/myproject.sock;
}
# added for let's encrypt
location /.well-known/ {
   root /home/sammy/myproject;
   allow all;
}
}

I tried this additional block:

server {
listen 80;
server_name www.example.com;
return 301 https://$server_name$request_uri;
...
}

This didn't seem to work though. I thought perhaps I should change this to listen on 443, but wasn't sure how that would affect the ssl server block and default_server directive?

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 3.0

The $server_name refers to the server name you have defined in the virtual host block. Therefore your additional block causes a redirect cycle redirecting back to itself.

You have to use a literal domain name there instead of a variable.

For SSL domain with www, you have to add listen 443 ssl; to the block and certificate values.

So, this should be your third block:

server {
    listen 80;
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
    include snippets/ssl-example.com.conf;
    include snippets/ssl-params.conf;
    ...
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-01-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。