Nginx环境下PHP应用CSS文件404错误排查求助
解决Nginx部署PHP应用时CSS文件404的问题
问题分析
访问/css/index.css时跳转到PHP的404页面,核心原因是Nginx没有优先处理静态文件请求,导致请求被转发到PHP路由,而PHP路由未匹配该路径,同时可能存在Nginx无法访问静态文件的问题。
解决方案
1. 确保Nginx能访问静态文件
你的Nginx容器和PHP容器是分离的,静态文件(css、images)存储在PHP容器目录中,Nginx容器需要挂载这些文件才能直接读取:
修改docker-compose.yml,给Nginx服务添加静态文件挂载:
services: nginx: build: ./nginx ports: - "80:80" volumes: # 挂载CSS和图片目录到Nginx容器 - ./php/css:/var/www/html/css - ./php/images:/var/www/html/images # 挂载Nginx配置文件 - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf depends_on: - php-fpm php-fpm: build: ./php volumes: - ./php:/var/www/html
2. 修正Nginx配置,优先处理静态资源
调整Nginx配置的location顺序,给静态资源路径添加^~前缀,确保Nginx优先匹配并处理静态文件请求,不会转发到PHP路由:
修改后的nginx.conf:
server { listen 80 default_server; server_name localhost; root /var/www/html; index index.php; error_page 404 /pages/404.php; # 优先匹配CSS目录,^~表示跳过后续正则匹配 location ^~ /css/ { expires 30d; } # 优先匹配图片目录 location ^~ /images/ { expires 30d; } # PHP文件处理 location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass php-fpm:9000; fastcgi_index index.php; } # PHP路由兜底 location / { try_files $uri $uri/ /index.php?$query_string; } }
3. 检查PHP页面中CSS的引用路径
确保PHP页面(如home.php)中使用绝对路径引用CSS:
<link rel="stylesheet" href="/css/index.css">
为什么之前的配置失效?
- 原Nginx配置中,静态资源的location没有设置优先级,兜底的
location /会将未匹配的请求转发到index.php,而PHP路由没有/css/index.css的匹配规则,因此返回404。 - 如果Nginx容器未挂载静态文件,即使配置正确,也会因找不到文件触发
try_files规则,最终转到PHP路由。
内容的提问来源于stack exchange,提问作者MaxPW777
相关产品推荐
相关产品推荐

