Nginx站点目录切换及特定URL路由规则配置求助
Nginx 配置实现主站切换与特定URL分流
核心思路
利用Nginx的location匹配优先级,先拦截/jp/开头的请求,转发到旧站点live_website;剩余所有请求默认转发到新站点new_website。
具体操作步骤
1. 备份现有配置
先备份当前abc.com的Nginx配置,避免误操作导致站点故障:
cp /etc/nginx/sites-available/abc.com /etc/nginx/sites-available/abc.com.bak
2. 编辑站点配置文件
打开abc.com的配置文件进行修改:
vim /etc/nginx/sites-available/abc.com
替换或修改server块内容为以下配置(根据实际SSL、PHP版本调整细节):
server { listen 80; listen [::]:80; listen 443 ssl http2; listen [::]:443 ssl http2; server_name abc.com www.abc.com; # 保留原有SSL证书配置 ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; # 默认主站指向new_website root /var/www/new_website; index index.php index.html index.htm; # 优先匹配/jp/开头的请求,映射到live_website根目录 location ^~ /jp/ { alias /var/www/live_website/; index index.php index.html index.htm; # WordPress伪静态规则 try_files $uri $uri/ /index.php?$args; # 处理/jp/路径下的PHP请求 location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $request_filename; } } # 默认请求处理(new_website站点) location / { try_files $uri $uri/ /index.php?$args; } # 处理new_website的PHP请求 location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; } # 禁止访问隐藏文件 location ~ /\.ht { deny all; } }
3. 调整WordPress站点设置
修改live_website目录下的WordPress配置,确保站点URL匹配/jp/路径:
打开/var/www/live_website/wp-config.php,添加以下两行:
define('WP_HOME', 'https://abc.com/jp/'); define('WP_SITEURL', 'https://abc.com/jp/');
也可登录该WordPress后台,在「设置-常规」中直接修改「WordPress地址(URL)」和「站点地址(URL)」为https://abc.com/jp/。
4. 验证配置并重启Nginx
测试配置文件语法是否正确:
nginx -t
如果提示test is successful,重启Nginx使配置生效:
systemctl restart nginx
注意事项
- 若PHP版本不是7.4,需修改
fastcgi_pass中的路径(例如php8.1-fpm.sock)。 - 确保
live_website与new_website目录权限一致,避免Nginx无法读取文件。 - 测试前清空浏览器缓存,避免旧缓存影响结果。
内容的提问来源于stack exchange,提问作者user15373325
相关产品推荐
相关产品推荐

