nginx URL重写失败

时间:2020-07-14 06:58:44

标签: nginx url-rewriting

我正在尝试将.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;
    }
}

1 个答案:

答案 0 :(得分:0)

我不知道您的if ($query_string块是做什么用的,所以我将忽略它们。

如果要在不同的rewrite...last块中处理重写的URI,请使用location,例如使用以.php结尾的URI。所有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;
    ...
}

有关if的使用,请参见this caution