温馨提示×

CentOS Laravel如何设置伪静态

小樊
38
2026-07-19 16:05:35
栏目: 智能运维

CentOS 上部署 Laravel 时,伪静态(URL Rewrite)通常是通过 NginxApache 实现的。下面分别给出两种常见环境的配置方法,你可以按自己使用的 Web 服务器选择。


一、使用 Nginx(推荐 ✅)

1️⃣ 环境示例

  • CentOS 7 / 8
  • Nginx
  • PHP-FPM
  • Laravel 项目路径:/www/wwwroot/laravel

2️⃣ Nginx 伪静态配置(核心)

编辑 Nginx 站点配置(如 /etc/nginx/conf.d/laravel.confnginx.conf):

server {
    listen 80;
    server_name yourdomain.com;
    root /www/wwwroot/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;

这行就是 Laravel 的伪静态核心。


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 /www/wwwroot/laravel/public

    <Directory /www/wwwroot/laravel/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

3️⃣ Laravel 自带 .htaccess

Laravel public/.htaccess 默认已存在,内容如下(无需修改):

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

4️⃣ 重启 Apache

systemctl restart httpd

三、常见问题排查

✅ 1. 访问出现 404

  • 确认访问的是 /public
  • Nginx 没有 try_files
  • Apache 未开启 AllowOverride All

✅ 2. 权限问题

chown -R nginx:nginx /www/wwwroot/laravel
chmod -R 755 /www/wwwroot/laravel

✅ 3. SELinux(CentOS 常见)

setenforce 0  # 临时关闭
# 或
setsebool -P httpd_read_user_content 1

四、宝塔面板用户(补充)

如果你使用的是 宝塔 + CentOS

  1. 网站 → 设置 → 伪静态
  2. 选择 Laravel
  3. 或手动填写:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

如果你愿意,可以告诉我:

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

我可以给你一份完全贴合你环境的配置

0