Docker+NGINX环境下PHP网站无法加载CSS文件求助
PHP网站引入header.php后CSS无法加载问题
问题描述
开发的PHP网站单独访问index.php时能正常显示测试内容,但引入header.php后,所有CSS文件均无法加载。这套方案此前可正常运行,怀疑可能需要更换Docker中的PHP引擎(比如php:8.1.0-fpm),寻求解决帮助。
相关配置与代码
Docker-compose配置
services: web: image: nginx:latest ports: - "8000:8000" volumes: - ./nginx/conf.d/default.conf:/etc/nginx/conf.d/dfault.conf app: build: dockerfile: dockerfile volumes: - ./app:/app
Dockerfile配置
FROM php:8.1-fpm-alpine RUN docker-php-ext-install
header.php代码(最后一行为CSS文件链接)
<?php include 'static_settings.php'; ?> <??> <!DOCTYPE html> <html lang="en"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="keywords" content="<?php echo $metaKeywords ?>"> <meta name="description" content="<?php echo $metaDescription ?>"> <meta property="og:description" content="<?php echo $metaDescription ?>" /> <meta property="og:locale" content="en_US" /> <meta property="og:title" content="<? echo $name ?>" /> <meta property="og:site_name" content="<? echo $name ?>" /> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link rel="icon" href="#"> <title><? echo $name ?>| <? echo $title ?></title> <!-- Font Awesome --> <script src="https://kit.fontawesome.com/756891195a.js" crossorigin="anonymous"></script> <!-- STYLES --> <link href="css/custom.css" rel="stylesheet"/>
index.php代码
<? $title = "Home"; $metaKeywords = "Home, apartment, living, Glenridge Heights, kitchens, amenities, enclosed garages, storage units, community, neighbors, life, applicances"; $metaDescription = "Glenridge Heights is a gated, swim community of townhomes in Sandy Springs, inside I-285"; include 'header.php' ?> <h1 class="text-center">TEST header</h1> <p>what is going on here</p> <? include 'footer.php' ?>
网站目录结构
app ├── css ├── js ├── index.php ├── header.php └── footer.php
排查与解决方向
- 修正Nginx配置挂载路径:docker-compose中Nginx的配置文件挂载路径拼写错误,
/etc/nginx/conf.d/dfault.conf应为/etc/nginx/conf.d/default.conf,错误会导致Nginx加载不到正确配置,静态资源请求无法被正常处理。 - 完善Nginx静态资源路由:确保Nginx的
default.conf中配置静态资源直接处理规则,避免静态文件请求经过PHP-FPM。示例配置:
server { listen 8000; root /app; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass app:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # 直接处理静态资源,避免解析错误 location ~* \.(css|js|png|jpg|jpeg|gif|ico)$ { expires 1y; add_header Cache-Control "public, immutable"; } }
- 修复header.php语法错误:header.php中的
<??>是无效PHP标签,会导致PHP解析中断,删除该行即可。 - 验证CSS路径正确性:确认
css/custom.css的相对路径基于网站根目录(app/),当前目录结构正确,需配合Nginx的root配置确保路径解析无误。 - 尝试更换PHP镜像版本:若以上配置修正后仍有问题,可将Dockerfile中的镜像更换为
php:8.1.0-fpm-alpine,排查版本兼容问题,但优先解决前面的配置错误,这些是更可能的问题根源。
内容的提问来源于stack exchange,提问作者Andrew Buccellato
相关产品推荐
相关产品推荐

