【问题标题】:nginx url rewrite getting failednginx url重写失败
【发布时间】:2020-07-14 16:09:36
【问题描述】:

我正在尝试将我的 .htaccess 规则迁移到 nginx。我已经尝试了几乎所有关于 SO & url rewriter 的问题,但没有成功。简而言之,我想转换以下动态网址:

来自

[1] - https://vc.test/results.php?url=ngo-service
[2] - https://vc.test/jobs.php?d=17&t=oil-&-gas
[3] - https://vc.test/jobs.php?d=17

[1] - https://vc.test/ngo-service
[2] - https://vc.test/17/oil-&-gas
[3] - https://vc.test/17

请求帮助以解决此问题。

我的 nginx 努力

server {
    listen      127.0.0.1:80;
    listen      127.0.0.1:443 ssl http2;
    ssl_certificate_key "d:/winnmp/conf/opensslCA/selfsigned/vc.test+4-key.pem";
    ssl_certificate "d:/winnmp/conf/opensslCA/selfsigned/vc.test+4.pem";    
    server_name     vc.test;
    root    "d:/winnmp/www/vc";
        
    ## Access Restrictions
    allow       127.0.0.1;
    deny        all;
        
    autoindex on;

    location / {
        index index.html index.htm index.php;
        try_files $uri $uri.html $uri/ @extensionless-php;

        if ($query_string ~* "fbclid="){
            rewrite ^(.*)$ /$1? redirect;
            break;
        }
        
        if ($query_string ~* "url="){
            rewrite ^(.*)$ /%1? redirect;
            rewrite ^/(.*)$ /results.php?url=$1 permanent;
            break;
        }

        rewrite ^/([0-9]+)/(.*)?$ jobs.php?d=$1&t=$2 break;
        rewrite ^/([0-9]+)?$ jobs.php?d=$1 break;

    }

    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include     nginx.fastcgi.conf;
        include     nginx.redis.conf;
        fastcgi_pass    php_farm;
        fastcgi_hide_header X-Powered-By;
    }
}

【问题讨论】:

  • 感谢@RichardSmith,您的建议解决了 [2] 和 [3] 的 url 问题。 [1] 网址有什么想法吗?

标签: nginx url-rewriting


【解决方案1】:

我不知道你的 if ($query_string 块是干什么用的,所以我会忽略它们。

如果要在不同的 location 块中处理重写的 URI,例如使用以 .php 结尾的 URI,则使用 rewrite...last。所有 Nginx URI 都以 / 开头,例如,使用 /jobs.php 而不是 jobs.php

您可以将rewrite 语句列表放在location / 块中,它们将按顺序进行评估,直到找到匹配项。如果未找到匹配项,则将评估 try_files 语句。 这就是重写模块的工作原理!

但是,第一个重写规则过于笼统,可能会破坏一些旨在由 try_files 语句实现的 URI。更好的解决方案可能是将所有 rewrite 语句放入同一个名为 location 的块中。

例如:

index index.html index.htm index.php;

location / {
    try_files $uri $uri.html $uri/ @rewrite;
}
location @rewrite {
    if (-f $document_root$uri.php) {
        rewrite ^ $uri.php last;
    }
    rewrite ^/([0-9]+)/(.+)$ /jobs.php?d=$1&t=$2 last;
    rewrite ^/([0-9]+)$ /jobs.php?d=$1 last;
    rewrite ^/([^/]+)$ /results.php?url=$1 last;
    return 404;
}
location ~ \.php$ {
    try_files $uri =404;
    ...
}

请参阅this caution 了解if 的使用。

【讨论】:

  • 谢谢@RichardSmith。正确地作为您的假设,try_files 不会自动将 {vc.test/results.php?url=ngo-service} 重定向到 {vc.test/ngo-service} 但上述帮助使此 url 可以通过两种方式访问​​。通过一些更改,我可以自己完成这项工作。再次感谢您的热心帮助:-)
猜你喜欢
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多