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

Nginx: redirect non-www https to https://www

· 52CE 我爱测

I'm having some issues when trying to redirect https://example.com to https://www.example.com . It simple gives me a redirect loop. This is my site's nginx configuration I had prior to the changes I made, which is located at /etc…

问题原文

原帖链接 · Tharindu Pramuditha · CC BY-SA 4.0

I'm having some issues when trying to redirect https://example.com to https://www.example.com. It simple gives me a redirect loop.

This is my site's nginx configuration I had prior to the changes I made, which is located at /etc/nginx/sites-available.

Can somebody tell me how to implement the redirection correctly using this configuration altered with the new redirection directives.

server {

listen 443 ssl http2;
listen [::]:443 ssl http2;

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

root /var/www/example.com/public_html;
index index.php;
server_name example.com www.example.com;

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}

}

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    return 301 https://$server_name$request_uri;
}

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

First, you need to remove example.com from the server_name directive of your main server block.

Second, you need to listen for https connections in the server block that performs the redirection.

For example:

ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name www.example.com;

    ...
}

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;

    server_name example.com;

    return 301 https://www.$server_name$request_uri;
}

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

资料来源与适用范围

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

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

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