在 CentOS 上设置 Laravel 伪静态(URL Rewrite),主要取决于你使用的 Web 服务器。Laravel 官方推荐 Nginx 或 Apache,下面分别说明。
假设你使用的是 LNMP / 宝塔 / 手动编译 Nginx,站点配置文件通常在:
/etc/nginx/conf.d/yourdomain.conf
或
/etc/nginx/sites-available/yourdomain
server {
listen 80;
server_name yourdomain.com;
root /var/www/laravel/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
✅ 重点这一行就是伪静态核心:
try_files $uri $uri/ /index.php?$query_string;
nginx -t
systemctl reload nginx
httpd -M | grep rewrite
如果没有,开启:
vi /etc/httpd/conf/httpd.conf
去掉注释:
LoadModule rewrite_module modules/mod_rewrite.so
示例:
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/laravel/public
<Directory /var/www/laravel/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
⚠️ AllowOverride All 必须开启
.htaccessLaravel 默认已有:
/var/www/laravel/public/.htaccess
内容如下(一般不用改):
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
systemctl restart httpd
如果是 CentOS 7/8,访问 403 或路由失效,可能是 SELinux 问题。
setenforce 0
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_unified 1
chown -R nginx:nginx /var/www/laravel
# 或
chown -R apache:apache /var/www/laravel
chmod -R 755 /var/www/laravel
chmod -R 777 /var/www/laravel/storage
chmod -R 777 /var/www/laravel/bootstrap/cache
宝塔用户直接:
访问:
http://yourdomain.com/login
✅ 不出现 index.php,页面正常 → 成功
❌ 404 / 500 → 配置有误
如果你愿意,可以把以下信息发我,我可以给你精确配置: