Nginx 原生不支持 .htaccess 文件(这是 Apache 的特性),但我们可以通过将 Apache 的 rewrite 规则转换为 Nginx 的 rewrite 规则来实现类似功能。以下是详细配置方法:
找到 Apache 的 .htaccess 文件中的 rewrite 规则
例如 Apache 的规则可能如下:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [L]
转换为 Nginx 的 rewrite 规则
在 Nginx 的 server 配置块中添加:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
或者更详细的版本:
location / {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^/(.*)$ /index.php?$1 last;
}
使用在线转换工具
可以使用 htaccess to nginx converter 等在线工具自动转换。
转换后放入 Nginx 配置
将转换后的规则放入 Nginx 的 server 配置块中。
创建单独的规则文件
例如 /etc/nginx/rewrite_rules.conf
在 Nginx 配置中引入
server {
...
include /etc/nginx/rewrite_rules.conf;
...
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}
}
Nginx 配置修改后需要重载:
sudo nginx -t && sudo nginx -s reload
Nginx 的 rewrite 规则语法与 Apache 不同,主要区别:
rewrite
指令而不是 RewriteRule
^
和 $
包围last
对应 Apache 的 [L]
性能考虑:Nginx 直接配置 rewrite 规则比 Apache 的 .htaccess 性能更好,因为不需要每次请求都读取文件。
通过以上方法,您可以在 Nginx 中实现与 Apache 的 .htaccess 文件相同的伪静态功能。