温馨提示×

CentOS怎么设置Laravel伪静态

小樊
44
2026-08-29 16:32:41
栏目: 智能运维

CentOS 上设置 Laravel 伪静态(URL Rewrite),主要取决于你使用的 Web 服务器。Laravel 官方推荐 NginxApache,下面分别说明。


一、使用 Nginx(推荐 ✅)

1️⃣ 示例 Nginx 配置(通用)

假设你使用的是 LNMP / 宝塔 / 手动编译 Nginx,站点配置文件通常在:

/etc/nginx/conf.d/yourdomain.conf

/etc/nginx/sites-available/yourdomain

2️⃣ Laravel Nginx 配置

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;

3️⃣ 重载 Nginx

nginx -t
systemctl reload nginx

二、使用 Apache(httpd)

1️⃣ 确保开启 mod_rewrite

httpd -M | grep rewrite

如果没有,开启:

vi /etc/httpd/conf/httpd.conf

去掉注释:

LoadModule rewrite_module modules/mod_rewrite.so

2️⃣ 修改 Apache 虚拟主机配置

示例:

<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 必须开启


3️⃣ Laravel 自带 .htaccess

Laravel 默认已有:

/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>

4️⃣ 重启 Apache

systemctl restart httpd

三、SELinux 常见问题(CentOS 特有 ✅)

如果是 CentOS 7/8,访问 403 或路由失效,可能是 SELinux 问题。

临时关闭(测试用)

setenforce 0

永久允许 httpd

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

五、宝塔面板(如果你在用)

宝塔用户直接:

  1. 网站 → 设置
  2. 伪静态
  3. 选择 Laravel
  4. 保存即可

六、验证是否成功 ✅

访问:

http://yourdomain.com/login

✅ 不出现 index.php,页面正常 → 成功
❌ 404 / 500 → 配置有误


如果你愿意,可以把以下信息发我,我可以给你精确配置

  • CentOS 版本
  • Nginx / Apache
  • 是否使用宝塔
  • Laravel 版本

0