Nginx配置WWW转非WWW及HTTP转HTTPS时出现重定向过多错误
问题分析与解决方法
你遇到的重定向循环问题主要源于Azure App Service的流量架构特性和当前nginx配置的几个冲突点,以下是具体修复方案:
核心问题点
- Azure流量转发逻辑:Azure的HTTPS终止在前端网关完成,容器内部的nginx实际接收的是
HTTP请求(端口80),而非直接的HTTPS请求。你配置监听443端口无效,反而会导致路由匹配混乱。 - server_name匹配错误:443块的
server_name _是通用匹配,会和80块的域名规则冲突,引发循环。 - WordPress站点URL不匹配:如果WordPress后台设置的站点地址还是HTTP或带WWW,会和nginx的重定向规则互相触发循环。
修正后的nginx配置(/etc/nginx/conf.d/default.conf)
upstream php { server unix:/var/run/php/php-fpm.sock; #server 127.0.0.1:9000; } # 处理所有HTTP请求(Azure网关转发过来的请求都是80端口) server { listen 80; server_name your-domain.com www.your-domain.com; # 替换为实际域名 # 先处理WWW转非WWW,再强制HTTPS if ($host = www.your-domain.com) { return 301 https://your-domain.com$request_uri; } # 检查Azure转发的协议头,确保跳转到HTTPS if ($http_x_forwarded_proto != "https") { return 301 https://your-domain.com$request_uri; } # 站点根目录与原有配置一致 root /home/site/wwwroot; index index.php; location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } # phpMyAdmin配置保留 location /phpmyadmin { root /home/; index index.php index.html index.htm; location ~ ^/phpmyadmin/(.+\.php)$ { try_files $uri =404; root /home/; fastcgi_pass unix:/var/run/php/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ { root /home/; } } location /phpMyAdmin { rewrite ^/* /phpmyadmin last; } sendfile off; set $skip_cache 0; # 缓存规则保留原有配置 if ($request_method = POST) { set $skip_cache 1; } if ($query_string != "") { set $skip_cache 1; } if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { set $skip_cache 1; } if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; } if ($request_uri ~* "/(cart|checkout|my-account)/*$") { set $skip_cache 1; } location / { try_files $uri $uri/ /index.php?$args; } location ~* \.php$ { include fastcgi.conf; include fastcgi_params; fastcgi_intercept_errors on; fastcgi_pass php; fastcgi_read_timeout 300; fastcgi_cache_bypass $skip_cache; fastcgi_no_cache $skip_cache; fastcgi_cache off; fastcgi_cache_valid 60m; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; } }
额外必须检查的配置
WordPress站点URL同步:
- 修改
wp-config.php,添加以下两行(替换为你的HTTPS非WWW域名):define('WP_HOME', 'https://your-domain.com'); define('WP_SITEURL', 'https://your-domain.com'); - 或者登录WordPress后台,在「设置」→「常规」中把「WordPress地址(URL)」和「站点地址(URL)」都改为
https://your-domain.com。
- 修改
其他可能的配置文件:
- 检查
/etc/nginx/modules-enabled/下的配置文件,确保没有额外的重定向规则; - 如果使用了缓存插件(如WP Rocket、W3 Total Cache),需要清空缓存并同步插件内的HTTPS/域名设置。
- 检查
验证方法
修改配置后重启nginx:
nginx -s reload
然后用浏览器访问http://www.your-domain.com,检查是否能正确跳转到https://your-domain.com,且无循环重定向提示。
内容的提问来源于stack exchange,提问作者Don Chambers
相关产品推荐
相关产品推荐

