简体   繁体   中英

nginx - proxy/rewrite based on location

I am trying to redirect all requests beginning with /api/ to a node server on localhost. I've been unable to get nginx to rewrite the request properly.

My server.conf (I included the whole file in case there is something conflicting I'm not noticing):

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.

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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