nginx URL重写失败

科技世界

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

[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;
    }
}
理查德·史密斯

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

使用rewrite...last,如果重写的URI是在不同的被处理location块,例如用URI的结尾.php所有Nginx URI都以前置字符开头/,例如use/jobs.php和not 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章