简体   繁体   English

nginx-基于位置的代理/重写

[英]nginx - proxy/rewrite based on location

I am trying to redirect all requests beginning with /api/ to a node server on localhost. 我试图将所有以/ api /开头的请求重定向到localhost上的节点服务器。 I've been unable to get nginx to rewrite the request properly. 我一直无法让nginx正确重写请求。

My server.conf (I included the whole file in case there is something conflicting I'm not noticing): 我的server.conf(我包括了整个文件,以防万一我不注意有冲突):

server {
    listen 80;

    root /var/www/sites/my.server;
    index index.php index.html index.htm;

    server_name .my.server;
    access_log /var/log/nginx/my.server-access.log;
    error_log /var/log/nginx/my.server-error.log;

    location / {
            try_files $uri $uri/ /index.html;
    }

    ## Redirect api to node server
    location /api {
            rewrite ^/api/(.*)$ /$1 last;
            proxy_pass      http://127.0.0.1:3030/;
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
          root /usr/share/nginx/www;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    if (!-e $request_filename){
        rewrite ^(.*)$ /index.php?q=$1 last;
        break;
    }

    # SSL Related Setup
    listen 443 ssl;
    ssl on;
    ssl_certificate /etc/ssl/certs/ssl-bundle.crt;
    ssl_certificate_key /etc/ssl/private/my.server.key;

    #enables all versions of TLS, but not SSLv2 or 3 which are weak and now deprecated.
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    #Disables all weak ciphers
    ssl_ciphers RC4:HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
}

Using this config, http://my.server/api is redirected properly to the node server, but http://my.server/api/jobs is not. 使用此配置, http://my.server/api被正确重定向到节点服务器,而http://my.server/api/jobs没有被重定向。

After much trial and error and searching, I found the following works: 经过反复试验和搜索,我发现以下作品:

location ^~ /api/ {
        rewrite ^/api/(.*) /$1 break;
        proxy_pass        http://127.0.0.1:3030/;
        proxy_set_header  Host            $host;
        proxy_set_header  X-Real-IP       $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM