XAMPP正常运行的网站在Apache2中访问localhost/login报404错误
环境:PHP 7.4.32、Ubuntu 22.04
网站在Windows和Linux版XAMPP中测试正常,访问localhost/时会要求输入账号密码,之后跳转到localhost/login。但部署到Apache2服务器后,访问localhost/login出现404页面未找到错误;访问localhost/app/views/partials/时,显示带网站真实布局的404错误,且日志中无任何报错。已尝试修改.htaccess文件和权限,问题依旧。
相关配置文件
Config.php
//Application resource access status define("AUTHORIZED", 200); define("UNAUTHORIZED", 401); define("NOROLE", 404); define("FORBIDDEN", 403); // Application Files and Directories define("IMG_DIR", "assets/images/"); define("FONTS_DIR", "assets/fonts/"); define("SITE_FAVICON", IMG_DIR . "favicon.jpg"); define("SITE_LOGO", IMG_DIR . "logo.jpg"); define("CSS_DIR", SITE_ADDR . "assets/css/"); define("JS_DIR", SITE_ADDR . "assets/js/"); define("APP_DIR", "app/"); define("SYSTEM_DIR", "system/"); define("HELPERS_DIR", "helpers/"); define("LIBS_DIR", "libs/"); define("LANGS_DIR", "languages/"); define("MODELS_DIR", APP_DIR . "models/"); define("CONTROLLERS_DIR", APP_DIR . "controllers/"); define("VIEWS_DIR", APP_DIR . "views/"); define("LAYOUTS_DIR", VIEWS_DIR . "layouts/"); define("PAGES_DIR", VIEWS_DIR . "partials/"); define("AUDIT_LOGS_DIR", "logs/");
.htaccess
RewriteEngine on Options -Indexes RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?request_uri=$1 [NC,L,QSA,B]
website.conf
<VirtualHost *:80> ServerName localhost ServerAlias localhost ServerAdmin webmaster@localhost DocumentRoot /var/www/website ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
启用Apache重写模块
Ubuntu默认Apache未开启rewrite模块,执行以下命令:sudo a2enmod rewrite sudo systemctl restart apache2配置VirtualHost允许.htaccess生效
修改website.conf,在<VirtualHost>块内添加目录权限配置,允许.htaccess覆盖规则:<VirtualHost *:80> ServerName localhost ServerAlias localhost ServerAdmin webmaster@localhost DocumentRoot /var/www/website ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/website> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>修改完成后重启Apache:
sudo systemctl restart apache2检查
SITE_ADDR常量定义
Config.php中使用了SITE_ADDR但未给出定义,需确认该常量是否在其他配置文件中正确设置,示例:define("SITE_ADDR", "http://localhost/");错误的
SITE_ADDR会导致资源路径错误,间接引发路由解析问题。验证网站文件权限
确保Apache用户(默认是www-data)拥有网站目录的读取权限:sudo chown -R www-data:www-data /var/www/website sudo chmod -R 755 /var/www/website调试重写规则
开启Apache重写日志排查规则执行情况,在website.conf的<VirtualHost>块内添加:RewriteLog ${APACHE_LOG_DIR}/rewrite.log RewriteLogLevel 3重启Apache后访问
localhost/login,查看/var/log/apache2/rewrite.log,确认请求是否正确转发到index.php。检查路由逻辑
确认网站路由处理逻辑(通常在index.php或核心控制器中)是否正确解析request_uri参数,比如是否存在处理login请求的控制器或视图文件。
内容的提问来源于stack exchange,提问作者Worst

