当你在 ThinkPHP 中设置了运行目录为 /public
后,可能会遇到 404 错误。这通常是因为 Web 服务器的配置问题导致的。以下是解决这个问题的几个步骤:
1. 修改 .htaccess
文件
如果你使用的是 Apache 服务器,需要确保 .htaccess
文件正确配置。在项目根目录下创建或修改 .htaccess
文件,内容如下:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /public/
# 如果请求资源不存在,则交给 index.php 处理
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]
</IfModule>
2. 修改 Nginx 配置文件
如果你使用的是 Nginx 服务器,需要修改 Nginx 的配置文件。在 nginx.conf
或者站点配置文件中添加或修改以下内容:
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/project/public; # 指定项目的 public 目录
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 根据实际 PHP 版本和配置修改
}
}
3. 修改 ThinkPHP 配置
确保 ThinkPHP 的配置文件中指定了正确的运行目录。在 config.php
文件中添加或修改以下内容:
return [
// 运行目录
'app_dir' => 'public',
// 应用基础路径
'base_path' => __DIR__ . '/../',
// 应用入口文件
'entry_file' => 'index.php',
];
4. 重启 Web 服务器
-
Apache:重启 Apache 服务。
shsudo service apache2 restart
-
Nginx:重启 Nginx 服务。
shsudo service nginx restart
5. 测试访问
- 在浏览器中访问你的网站,确保所有配置生效并且没有 404 错误。
总结
通过以上步骤,你可以解决 ThinkPHP 设置运行目录为 /public
后出现的 404 错误。确保 Web 服务器的配置正确,并且 ThinkPHP 的配置文件也进行了相应的修改。这样可以确保应用能够正常运行。