You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTTP/无协议/WWW子域名访问重定向至主域名问题求助

解决子域名访问重定向丢失问题

问题根源

当前Nginx的80端口配置为默认服务器,所有HTTP请求都进入该块;你之前添加的return 301 https://$host$request_uri;触发重定向循环,是因为缺少对应的HTTPS配置块,导致HTTPS请求又回落到默认80端口规则,形成闭环。同时带WWW前缀的子域名未被正确处理,才会跳转到主域名。

解决方案

步骤1:重构HTTP(80端口)配置,仅做HTTPS重定向

将原80端口的业务逻辑剥离,改成专门的重定向规则:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    # 保留原请求域名(包括子域名),统一重定向到HTTPS
    return 301 https://$host$request_uri;
}

步骤2:新增HTTPS(443端口)配置,处理所有域名

创建独立的HTTPS配置块,覆盖主域名、子域名及带WWW的子域名场景:

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

    # 匹配主域名+所有子域名(含带WWW的子域名)
    server_name allrestaurants.us *.allrestaurants.us;

    # 替换为你的SSL证书路径(需支持通配符或包含所有子域名)
    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    root /var/www/allrest/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    charset utf-8;
    index index.html index.htm index.php;

    # 把带WWW的子域名重定向到不带WWW的对应子域名
    if ($host ~* ^www\.(.*)\.allrestaurants\.us$) {
        return 301 https://$1.allrestaurants.us$request_uri;
    }

    # Zabbix状态页配置
    location = /basic_status {
        stub_status;
        allow 127.0.0.1;
        allow ::1;
        deny all;
    }

    # PHP-FPM状态页配置
    location ~ ^/(status|ping)$ {
        access_log off;
        allow 127.0.0.1;
        deny all;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;

        fastcgi_connect_timeout 3600;
        fastcgi_send_timeout 3600;
        fastcgi_read_timeout 3600;
        fastcgi_buffering off;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    location ~* \.(png|jpg|jpeg|gif|svg|ico)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }

    error_log /var/log/nginx/allrest_error.log;
    access_log /var/log/nginx/allrest_access.log;
}

步骤3:验证并重启Nginx

  1. 检查配置合法性:
nginx -t
  1. 重启Nginx生效:
systemctl restart nginx

Laravel路由优化

由于Nginx已经提前将带WWW的子域名重定向到不带WWW的版本,你可以保留原路由,也可以删除带WWW的路由块,减少冗余逻辑。

内容的提问来源于stack exchange,提问作者Abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:40:32