温馨提示×

ubuntu thinkphp如何设置伪静态

小樊
40
2026-10-04 14:23:48
栏目: 编程语言

在 Ubuntu + ThinkPHP 环境下设置伪静态,通常取决于你使用的 Web 服务器(Apache 或 Nginx) 以及 ThinkPHP 版本(5.x / 6.x / 8.x)。下面分别说明。


一、Apache 下设置伪静态(最常见)

1️⃣ 开启 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

2️⃣ 修改 Apache 配置(允许 .htaccess)

编辑站点配置(示例):

sudo nano /etc/apache2/sites-enabled/000-default.conf

在 <VirtualHost> 中添加:

<Directory /var/www/html>
    AllowOverride All
</Directory>

重启 Apache:

sudo systemctl restart apache2

3️⃣ 在 ThinkPHP 根目录添加 .htaccess

(通常是 public/.htaccess)

<IfModule mod_rewrite.c>
    Options +FollowSymlinks -Multiviews
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

✅ 访问示例:

http://域名/index/index/hello

二、Nginx 下设置伪静态(推荐生产环境)

1️⃣ 编辑 Nginx 站点配置

sudo nano /etc/nginx/sites-enabled/default

2️⃣ 配置示例(ThinkPHP)

server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html/public;

    index index.php index.html;

    location / {
        if (!-e $request_filename) {
            rewrite ^(.*)$ /index.php?s=/$1 last;
            break;
        }
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

⚠️ ThinkPHP 6/8 推荐指向 public 目录

3️⃣ 测试并重载

sudo nginx -t
sudo systemctl reload nginx

三、ThinkPHP 自身配置

关闭强制后缀(可选)

config/app.php

'url_html_suffix' => '',

四、常见问题排查

✅ 404

  • 未开启 rewrite
  • Nginx 没指向 public
  • .htaccess 未生效

✅ 首页正常,其他页面 404

  • 伪静态规则不正确
  • Apache AllowOverride 未开

✅ 出现 index.php 无法隐藏

  • 检查 rewrite 是否生效

如果你告诉我:

  • ✅ ThinkPHP 版本
  • ✅ Apache 还是 Nginx
  • ✅ Ubuntu 版本

我可以给你精确到行的配置。

0 踩