将Apache重写规则转换为Nginx

时间:2016-03-04 14:59:07

标签: apache .htaccess mod-rewrite nginx rewrite

如何将这些规则从.htaccess(apache)转换为Nginx conf?

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.html
RewriteRule ^([^/]+)/([^/]+)/$ /$1-$2.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

我使用这些规则重写请求,如:

/someurl1/ => someurl.html (/company/ to /company.html
/someurl1/someurl2/ => someurl-someurl2.html (/projects/3/ to /projects-3.html)

我已经尝试了这个(不起作用):

if (!-e $request_filename) {
  rewrite ^/([^/]+)/$ /$1.html;
  rewrite ^/([^/]+)/([^/]+)/$ /$1-$2.html;
}

try_files $uri $uri/ =404;

我哪里错了?

1 个答案:

答案 0 :(得分:1)

我测试过以下内容似乎有效:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/([^/]+)/$ /$1.html last;
    rewrite ^/([^/]+)/([^/]+)/$ /$1-$2.html last;
    return 404;
}

RewriteCond %{REQUEST_FILENAME} !-f测试实际上是由try_files指令完成的。

有关详细信息,请参阅this