PHP/Apache保留根路径前缀,解决服务器迁移后路径找不到问题
问题描述
数据库中存储的文件路径为/files/person_1/awatar.png,此前使用file_get_contents("/files/person_1/awatar.png")可正常读取文件。更换Web服务器后,PHP抛出"directory not found exception"异常。服务器实际文件路径为/var/www/public_html/new_service_xxxxx/files/awatar.png,要求不修改路径开头的/符号,需调整哪些配置?
当前Apache虚拟主机配置如下:
<VirtualHost *:80> ServerName test.new_service_xxxxx.pl ServerAlias www.new_service_xxxxx.pl DocumentRoot /var/www/public_html/new_service_xxxxx <Directory /var/www/public_html/new_service_xxxxxk> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <IfModule mod_dir.c> DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm index.php5 </IfModule> </VirtualHost>
解决方案
1. 修正虚拟主机配置中的目录路径错误
当前<Directory>指令的路径多了一个末尾的k,正确路径应为/var/www/public_html/new_service_xxxxx,先修正这个笔误,否则Apache无法正确识别网站根目录的权限配置。
2. 添加Alias指令映射路径
要让PHP中开头为/files的路径指向实际文件目录,需在Apache虚拟主机配置中添加Alias指令,将根路径下的/files映射到真实的文件存储目录:
<VirtualHost *:80> ServerName test.new_service_xxxxx.pl ServerAlias www.new_service_xxxxx.pl DocumentRoot /var/www/public_html/new_service_xxxxx # 添加Alias映射 Alias /files /var/www/public_html/new_service_xxxxx/files # 修正后的网站根目录权限配置 <Directory /var/www/public_html/new_service_xxxxx> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> # 新增映射目录的权限配置 <Directory /var/www/public_html/new_service_xxxxx/files> Options FollowSymLinks AllowOverride None Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <IfModule mod_dir.c> DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm index.php5 </IfModule> </VirtualHost>
3. 重启Apache服务
修改配置后,执行对应系统的命令重启Apache使配置生效:
# Debian/Ubuntu系统 sudo systemctl restart apache2 # CentOS/RHEL系统 sudo systemctl restart httpd
补充说明
Alias指令的作用是将PHP中使用的绝对路径(以/files开头)映射到服务器本地的真实文件目录,这样file_get_contents("/files/...")就能正确找到对应文件。- 必须为映射的目录添加
<Directory>权限配置,确保Apache有访问该目录的权限,避免出现权限拒绝类错误。
内容的提问来源于stack exchange,提问作者Blazej Kita
相关产品推荐
相关产品推荐

