问题描述
我已经在Apache上运行了我的网站多年,并且由于出于速度偏好而过渡到Nginx,所以我的htaccess重写规则破坏了我的网站。
我的网站内容是根据URL请求动态提供的-这是我的htaccess文件查找/访问量的方式。
RewriteEngine on
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/$ index.php?first_path=$1 [QSA]
这会将任何目录作为first_path参数传递给index.php。
通读Nginx文档进行URL重组后,我似乎无法弄清楚如何编写需求。
任何想法都会有所帮助。
解决方法
您可能会对this one之类的在线转换器感到有些运气,具体针对您的.htaccess
的在线转换器会产生:
server {
server_name example.com;
rewrite ^/([a-zA-Z0-9-z\-\_]+)/$ /index.php?first_path=$1;
}
自然,您还必须包括一个用于处理PHP的“处理程序”位置,这样更完整的配置应为:
server {
server_name example.com;
rewrite ^/([a-zA-Z0-9-z\-\_]+)/$ /index.php?first_path=$1;
location ~ \.php$ {
fastcgi_pass unix:/path/to/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
但是值得注意的是,NGINX的创建者本人Igor Sysoev不赞成使用rewrite
指令dismissing their use to old times when nested locations were not supported。
根据NGINX的作者,嵌套的位置允许隔离正则表达式,从而创建将来更易于维护的配置(尽管起初不一定更容易创建)。因此,在这种情况下,使用嵌套位置,相同的配置可能如下所示:
server {
server_name example.com;
location / {
location ~ ^/(?<dir>[a-zA-Z0-9-z\-\_]+)/$ {
fastcgi_pass unix:/path/to/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME /path/to/index.php;
fastcgi_param QUERY_STRING first_path=$dir
include fastcgi_params;
}
}
location ~ \.php$ {
fastcgi_pass unix:/path/to/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}