nginx反向代理配置问题?

小白刚入手nginx,望大n....
我在本地添加了:seren.proxy.cn、seren.html.cn 两个站点。
虽然代理能访问了,但访问“seren.html.cn”下的php文件却无法访问,奇怪 html能行。

clipboard.png

clipboard.png

像单纯写“seren.proxy.cn/api”是能访问index.php, 在“seren.proxy.cn/api”后面加上“index.php”又不行了真磨人啊

clipboard.png

seren.proxy.cn 配置

server {
        listen        80;
        server_name  www.seren.proxy.cn seren.proxy.cn;
        root   "F:/seren/www/proxy";
        location / {
            index index.php index.html;
            autoindex  off;
        }

        location /api/{
            rewrite ^/api/(.*)$ /$1 break;
            proxy_pass http://seren.html.cn;
        }

        location ~ .*\.(js|css|jpg|jpeg|gif|png|ico|pdf|txt)$ {
            proxy_pass http://seren.html.cn;
        }

        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9001;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

seren.html.cn 配置

server {
        listen        80;
        server_name  seren.html.cn;
        root   "F:/seren/www/proxyhtml";
        location / {
            index index.php index.html;
            autoindex  off;
        }
        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9001;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

阅读 3.1k
3 个回答

你这个完全就是 location匹配的顺序问题

你使用的是普通匹配, 普通匹配成功了不会停止匹配的, 如果同时也有正则匹配并且成功匹配到了, 那么就会优先使用正则匹配的结果

明显的, 你的url http://seren.proxy.cn/api/index.php 先匹配到了 location /api/,
但是因为这个规则只是普通匹配,所以又继续往下匹配, 这时又一个规则location ~ \.php(.*)$被匹配上了, 并且是正则匹配, 优先级比普通匹配要高
所以最终使用是这个规则, 自然也是这个规则来处理你的url

你一开始使用的url是http://seren.proxy.cn/api, 因为这个只满足一个匹配结果, 所以没有问题

解决方法很简单

加上^~, 让它变成精准的前缀匹配就可以了

location ^~ /api/{
    rewrite ^/api/(.*)$ /$1 break;
    proxy_pass http://seren.html.cn;
}     

精准前缀匹配是匹配到之后立即结束, 不往下继续匹配

你可以看看我的文章: https://www.xstnet.com/articl...

试试这样,不需要rewrite

location /api {
    proxy_pass http://seren.html.cn/; #后面加/,表示截断
}

试试这个php跳转, no input file...什么的是SCRIPT_FILENAME配置不对吧

location ~ [^/]\.php(/|$) {
    try_files $uri =502;
    fastcgi_pass   127.0.0.1:9001;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题