nginx 友好 URL 重写规则

nginx 友好 URL 重写规则

我在使用 nginx 将 .php 索引文件获取到友好 URL 时遇到了问题。

例如我的 Apache 设置运行完美:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([a-z]+)/([a-z\-]+)$ /$1/$2.php [L]
</IfModule>

RewriteBase /
RewriteCond %{HTTP_HOST} !^http://domain.local$ [NC]
RewriteRule ^(.*)$ http://domain.local$1 [L,R=301]
RewriteRule ^start index.php [L]
RewriteRule ^side2 side2.php [L]
RewriteRule ^side3 side3.php [L]
RewriteRule ^side4 side4.php [L]
RewriteRule ^side5 side5.php  [L]
RewriteRule ^side6 side6.php [L]

但如果我尝试将它们转换为 nginx,我根本无法让它工作。我搜索了一下,但没有找到。

这就是我尝试过的

location / {
rewrite ^/([a-z]+)/([a-z\-]+)$ /$1/$2.php break;
if ($http_host !~ "^domain.local$"){
rewrite ^(.*)$ http://domain.local/$1 redirect;
}
}
location /start {
rewrite ^/start /index.php break;
}
location /side1 {
rewrite ^/side1 /pages/side1/side1.php break;
}
location /side2 {
rewrite ^/side2 /pages/side2.php break;
}
location /side3 {
rewrite ^/side3 /pages/side3.php break;
}
location /side4 {
rewrite ^/side4 /pages/side4.php break;
}
location /side5 {
rewrite ^/side5 /pages/side6.php break;
}
location /side6 {
rewrite ^/side6 /form.php break;
}

我自己搞定了。

 rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
 if ($http_host !~* "^domain.local$"){
 set $rule_1 1$rule_1;
 }
 if ($rule_1 = "1"){
rewrite ^/(.*)$ http://domain.local/$1 permanent;
}
rewrite ^/start /index.php last;
rewrite ^/side1 /pages/side1/side1.php last;
rewrite ^/side2 /pages/side2.php last;
rewrite ^/side3 /pages/side3.php last;
rewrite ^/side4 / pages/side4.php last;
rewrite ^/side5 /pages/side5.php last;
rewrite ^/side6 /form.php last;

答案1

即使这种方法目前“有效”,但你做错的事情(确实)是错的。

server {

    listen X.X.X.X:80;
    server_name domain.local;

    location / {
        rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
        rewrite ^/start /index.php last;
        rewrite ^/side([2-6]) /pages/side$1.php last;
    }

   location ~ \.php$ {
       [ ... ]
   }

}


server {

    listen X.X.X.X:80 default_server;
    server_name _;
    return 301 http://domain.local$request_uri;

}

答案2

谢谢你的建议,

但是 side1 - side6 只是我想要的一些例子。

它将像开始论坛联系新闻等。

我现在已经对它进行了一些重建。

 location / {
    index   index.php;
    rewrite ^/([a-z]+)/([a-z-]+)$ /$1/$2.php last;
    rewrite ^/start /index.php last;
    rewrite ^/rent /pages/rent/rent.php last;
    rewrite ^/news /pages/news.php last;
    rewrite ^/info /pages/info.php last;
    rewrite ^/faq /pages/faq.php last;
    rewrite ^/contact /pages/contact.php last;
    rewrite ^/form /form.php last;

}

相关内容