【问题标题】:nginx - proxy/rewrite based on locationnginx - 基于位置的代理/重写
【发布时间】:2015-03-10 21:50:32
【问题描述】:

我正在尝试将所有以 /api/ 开头的请求重定向到本地主机上的节点服务器。我一直无法让 nginx 正确地重写请求。

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

使用此配置,http://my.server/api 被正确重定向到节点服务器,但 http://my.server/api/jobs 不是。

【问题讨论】:

    标签: nginx rewrite proxypass


    【解决方案1】:

    经过反复试验和搜索,我发现了以下作品:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2014-03-12
      • 2019-01-20
      • 2012-05-24
      • 2014-12-06
      • 1970-01-01
      • 2019-11-11
      • 2016-02-14
      相关资源
      最近更新 更多