NGINX单域名部署Codeigniter与HTML双站点无法同时生效问题求助
问题原因
- 根路径的location规则写法错误:你写的
location /*不符合Nginx的location匹配语法,正常匹配所有根路径请求应该用location /,/*的写法只会匹配路径开头带*的异常请求,导致根路径的静态站点规则根本没有生效。 - 路径匹配优先级冲突:Nginx的正则匹配优先级高于普通前缀匹配,你当前没有给
/shadows的location加^~修饰符,当访问/shadows下的资源时,可能会被其他规则拦截导致解析路径错误。 - alias与try_files搭配存在解析缺陷:Nginx中alias指令和try_files一起使用时会出现路径拼接错误的已知问题,优先用root指令调整路径结构可以规避这类坑。
修正后的配置
server { listen 80; listen [::]:80; # 根路径默认指向静态站点目录 root /var/www/html/home; server_name example.com; index index.html index.htm index.php; # 匹配/shadows开头的所有请求,^~ 表示匹配到后不再走后续正则匹配 location ^~ /shadows { # 用root规则,请求路径/shadows/xxx会自动拼接root路径得到/var/www/html/shadows/xxx root /var/www/html; try_files $uri $uri/ /shadows/index.php$is_args$args; # 内部单独处理shadows目录下的php请求,避免全局php规则解析路径错误 location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; } } # 根路径请求处理 location / { try_files $uri $uri/ /index.html; } # 全局其他php请求处理(静态站点若无php需求可删除) location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; } error_page 404 /error/404.php; fastcgi_intercept_errors on; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } }
生效操作
- 保存配置后执行
nginx -t检查配置语法是否正确 - 语法无误后执行
systemctl reload nginx重载配置即可
内容的提问来源于stack exchange,提问作者d7l2k4
相关产品推荐
相关产品推荐

