ThinkPHP URL 模式配置
相关配置已在 ThinkPHP 3.2.2 版本中验证通过,通常也适用于其他兼容版本。
第一步是调整应用配置文件。
将 'URL_CASE_INSENSITIVE' 设为 true,使 URL 不区分大小写(默认 false)。同时设置 'URL_MODEL' 为 2,即开启 REWRITE 模式。该参数支持 0(普通模式)、1(PATHINFO 模式)、2(REWRITE 模式)和 3(兼容模式),默认值为 PATHINFO 模式。
Nginx 服务器重写规则
针对 Nginx 服务器
推荐采用以下配置方案:
location / {
try_files $uri $uri/ /index.php?s=$uri&$args;
}
其逻辑为:若 $uri 对应的资源不存在,则尝试访问 $uri/;若目录也不存在,则重定向至 /index.php?s=$uri&$args。此逻辑可连续扩展多个 fallback。
try_files
语法: try_files file1 [file2 ... filen] fallback
默认值: 无
作用域: location
另一种写法示例如下:
try_files $uri = 404
这表示当 uri 无法成功访问时,直接返回 404 错误。
然而网上许多文章提供的配置方式如下:
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?/$1 last;
break;
}
}
实际上这种配置并不可行。
Apache 与 IIS 配置方法
针对 Apache 服务器
需在网站根目录下创建 .htaccess 文件并添加相应规则。
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
针对 IIS 服务器环境
若服务器支持 ISAPI_Rewrite,可在 httpd.ini 文件中添加以下内容: RewriteRule (.*)$ /index\.php\?s=$1 [I]
对于高版本 IIS,可在 web.config 中间插入 rewrite 节点进行配置。
附录
Nginx 完整配置文件示例
test.com.conf
server
{
listen 80;
server_name test.com;
index index.php index.html;
root /wwwroot/test.com/;
# unless the request is for a valid file (image, js, css, etc.), send to bootstrap
location / {
try_files $uri $uri/ /index.php?s=$uri&$args;
}
location ~ \.php
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
#fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
set $path_info "";
set $real_script_name $fastcgi_script_name;
if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
set $real_script_name $1;
set $path_info $2;
}
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
fastcgi_param SCRIPT_NAME $real_script_name;
fastcgi_param PATH_INFO $path_info;
}
location /status {
stub_status on;
access_log off;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 24h;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
if ( $fastcgi_script_name ~ \..*\/.*php ) {
return 403;
}
access_log logs/test.com_access.log main;
error_log logs/test.com_error.log notice;
}