Docker容器中Apache重写规则无法生效的问题求助
问题:Apache重写规则在PHP Docker容器中不生效,REST API路由返回404
我用PHP Apache Docker容器搭建了REST API,需要通过Apache重写规则将所有API请求路由到index.php(REST控制器),但访问http://localhost/xyz这类路径时始终返回404错误。已经参考大量教程和论坛问题,仍无法解决。
本地文件结构
php conf.d - error_reporting.ini - xdebug.ini Dockerfile index.php apache - apache2.conf docker-compose.yml
Dockerfile内容
FROM php:8.1-apache WORKDIR /var/www/html/ RUN pecl install xdebug \ && docker-php-ext-enable xdebug \ && a2enmod rewrite COPY . . EXPOSE 80
docker-compose.yml内容
services: php: build: ./php depends_on: - db container_name: php-apache ports: - 80:80 volumes: - ./php:/var/www/html - ./php/conf.d/xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini - ./php/conf.d/error_reporting.ini:/usr/local/etc/php/conf.d/error_reporting.ini - ./apache/apache2.conf:/etc/apache2/apache2.conf environment: MARIADB_HOST: localhost MARIADB_USER: root MARIADB_PASSWORD: top_very_secret MARIADB_DB: apidb adminer: image: adminer depends_on: - db restart: always ports: - 8080:8080 db: image: mariadb container_name: db volumes: - maria-db-storage:/var/lib/mysql environment: MARIADB_ROOT_PASSWORD: top_very_secret MARIADB_DATABASE: apidb volumes: maria-db-storage:
Apache配置修改
我从容器虚拟文件系统复制了默认的apache2.conf到本地,并添加了以下自定义指令:
# Custom directives start here # Set Server's name ServerName 'localhost' # Rewrite for routing of all requests through REST controller RewriteEngine On # If requested resource is index.php, do nothing RewriteRule ^index\.php$ - [L] # If requested resource is a file or directory that does not exist, reroute to REST # controller index.php RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d RewriteRule . /index.php [L]
已完成的排查
- 确认容器内的
apache2.conf已更新为本地修改后的版本 - 已启用
rewrite_module模块 - 执行
apachectl configtest显示配置语法正确 - 访问根路径
http://localhost正常,但重写规则未生效
疑问:是否和xdebug的9003端口通信有关?还有哪些配置遗漏了?
内容的提问来源于stack exchange,提问作者DevelJoe
相关产品推荐
相关产品推荐

