PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label nginx-reverse-proxy. Show all posts
Showing posts with label nginx-reverse-proxy. Show all posts

Wednesday, September 14, 2022

[FIXED] How to route the first URI segment using NGINX as a reverse-proxy?

 September 14, 2022     nginx, nginx-reverse-proxy, routes, segment, uri     No comments   

Issue

I'm trying to construct an architecture/infrastructure on Amazon Web Services. Today I have an EC2 working like a gateway, with NGINX on the background. Btw, I'm new with NGINX.

The last week I had this NGINX config file:

server {
    listen 80;

    # I put * for hide the real domain name
    server_name ******.com.ar www.******.com.ar;

    location / {
         proxy_set_header   X-Forwarded-For $remote_addr;
         proxy_set_header   Host $http_host;
         proxy_pass         "http://private.ip.1:80/";
    }
}

And it worked great! When I go to www.domain.com.ar, I get a redirect to private ip 1 on port 80.

But, nowdays, I need to adjust the config file a bit.

1) First, I need to redirect some known paths to private ip 1 (ex. /company, /portfolio, /services, /contact and subsequences: /company/ourvision, /services/software, /contact/workwithus). I'm using NodeJS, not PHP.

2) And if none of the before paths get a match, I need to get the first URI segment as a wildcard (ex. http://domain.com.ar/*) matching only this characters: A-z0-9 and send to private ip 2 on port 3000, also I need sending the wildcard word too (ex. http://private.ip.2:3000/wildcard-word)

I was only trying to success on my second point, but I couldn't deal with it.

server {
    listen 80;
    server_name ******.com.ar www.******.com.ar;

    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://private.ip.1:80/";
    }

    location ~ ^/(.*)/?$ { 
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass         "http://private.ip.2:3000/$1";
    }
}

But this isn't working. When I go to http://example.com.ar I go directly to the private ip 2 on port 3000. Btw, in another scenario, I get the follow error when I use the nginx -t command: "proxy_pass" cannot have URI part in location given by regular expression, or inside named location

So, can anyone help this noob to solve his problem? Thanks in advance. I will let the links that I was reading below:

  • nginx rule for wildcard url
  • nginx location based on uri path
  • How to do URL Redirects with Nginx
  • How to rewrite URI nginx reverse proxy using proxy_pass?
  • Understanding Nginx Server and Location Blocks (DigitalOcean)

Solution

You want to use the location / { ... } block as your wildcard, as it matches any URI that will not match another location block.

You do not need a URI component in the proxy_pass statement, as you are not modifying the URI before sending it upstream. See this document for details.

You can save on typing by specifying the proxy_set_header statements within the outer block and allowing them to be inherited by both location blocks. See this document for details.

For example:

proxy_set_header   X-Forwarded-For $remote_addr;
proxy_set_header   Host $http_host;

location ~ ^/(company|portfolio|services|contact|)(/|$) {
    proxy_pass         "http://private.ip.1:80";
}

location / {
    proxy_pass         "http://private.ip.2:3000";
}


Answered By - Richard Smith
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set proxy_http_version in LUA code before upstreaming the request in nginx

 September 14, 2022     lua, nginx, nginx-location, nginx-reverse-proxy, openresty     No comments   

Issue

I want to change the proxy http version in Lua code programmatically. Is there any way?

Yes, I know that we can set it via the nginx config file in the location/server block. Is there any way that I can do it using Lua dynamically per request?


Solution

Updated 14.10.2020

location / {
   content_by_lua_block {
       -- some logic here
       if flag then
          return ngx.exec("@http1_0")
       end
       return ngx.exec("@http1_1")
   }
}

location @http1_0 {
   proxy_pass ...;
   proxy_http_version 1.0;
   ...
}

location @http1_1 {
   proxy_pass ...;
   proxy_http_version 1.1;
   ...
}


Answered By - Alexander Altshuler
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why http://www.google.com is an invalid host?

 September 14, 2022     nginx, nginx-reverse-proxy     No comments   

Issue

i have this nginx.conf:

events {}

http {

  upstream search {
    server http://www.google.com weight=2;
    server http://www.duckduckgo.com weight=1;
  }

  server {
    listen 80;

    location /a {
      return 200 'hi';
      add_header Content-Type text/plain;
    }

    location /b {
      proxy_pass http://search;
    }
  }
}

when i try sudo systemctl reload nginx i see at /var/log/nginx/error.log:

2022/06/06 16:42:55 [emerg] 576712#576712: invalid host in upstream "http://www.google.com" in /etc/nginx/nginx.conf:6

i started my exemple out of here

i tried replacing http://www.google.com with http://8.8.8.8 but the error remained the same:

$ nginx -t
nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
2022/06/06 17:29:47 [emerg] 581155#581155: invalid host in upstream "http://8.8.8.8" in /etc/nginx/nginx.conf:6
nginx: configuration file /etc/nginx/nginx.conf test failed

Solution

since upstream doesn't expect protocol, removing it made it work:

upstream search {
  server www.google.com weight=2;
  server www.duckduckgo.com weight=1;
}


Answered By - rado
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to run my node app alongside my php application

 September 14, 2022     nginx, nginx-reverse-proxy, node.js, php, reverse-proxy     No comments   

Issue

I've been playing around with nginx and reverse proxy's to try figure out how to run my nodejs app alongside my php application. The node app is just a simple socket io chat app but i'd like it to run on chat.mydomain.com. Would someone be able to guide me in the right direction?

Thanks


Solution

You are looking for NGINX server blocks. You can create one proxy for your php app on yourdomain.com and another one for chat.yourdomain.com which points to your node app.



Answered By - Code Spirit
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, September 2, 2022

[FIXED] How can I remove the need for two docker containers which work together to use bridged networking?

 September 02, 2022     docker, nginx, nginx-reverse-proxy, postgresql, tomcat     No comments   

Issue

I have three docker containers:

1: nginx container accessible on port 8080 and not using bridged networking

2: xwiki container running tomcat accessible on port 8080 using bridged networking

3: Postgres container hosting the xwiki database and accessible on port 5432 using same bridged network as the xwiki container

I want to be able to set nginx to reverse proxy and load the xwiki site on a url such as http://site-root/xwiki but its not able to do this as its not on the same bridged network and I get a no route to host error...

All the hosts are accessible from a remote host using the docker hosts ip and the respective container port...

I have created xwiki and postgres containers that dont use bridged networking to test this but the xwiki tomcat server fails as xwiki cant find the postgres server and I get the below error as a tomcat exception:

java.net.UnknownHostException: postgres-db-server

Is there away to remove the need for using bridged networking for the xwiki and postgres containers and have them communicate using the docker hosts IP and their respective port numbers?

I'm thinking that I may need to edit the tomcat config in the xwiki container so that it points to the postgres server using the docker hosts IP and the postgres default port...

Can any one give me an idea of if this sounds like to right solution or if I am missing something with regard to the need for bridged networking?

I realise that a possible solution is to set the nginx container to use the same bridged networking but i also want the nginx service to be able to reverse proxy a node.js server running on the docker host... (not via docker)

Should I just containerise node and run all the containers using the same bridged network as this, logically should remove the problem, but I am concerned that it may cause other problems down the line...

The docker host is running on Centos 7

The commands used to manually run the containers as shown below:

Nginx

docker run -dti --name nginx-dev --hostname nginx-dev -p 80:80 -v /nginx/www:/usr/share/nginx/html:ro -v /nginx/conf:/etc/nginx -P -d nginx

Postgres

docker run --net=xwiki-nw --name postgres-db-server -p 5432:5432 -v /postgres/data:/var/lib/postgresql/data -e POSTGRES_ROOT_PASSWORD=xwiki -e POSTGRES_USER=xwiki -e POSTGRES_PASSWORD=xwiki -e POSTGRES_DB=xwiki -e POSTGRES_INITDB_ARGS="--encoding=UTF8" -d postgres:9.5

Xwiki

docker run --net=xwiki-nw --name xwiki -p 8080:8080 -v /xwiki:/usr/local/xwiki -e DB_USER=xwiki -e DB_PASSWORD=xwiki -e DB_DATABASE=xwiki -e DB_HOST=postgres-db-server xwiki:postgres-tomcat

Solution

Run

docker network connect xwiki nginx-dev 

And then you nginx container will be able to find the route to other two containers.



Answered By - Tarun Lalwani
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to write nginx rewrite rule for replacing query param in query string

 September 02, 2022     nginx, nginx-reverse-proxy     No comments   

Issue

folks!

We have following http request:

http://185.xxx.x.xx/auth/realms/master-realm/protocol/openid-connect/auth?response_type=code&client_id=regportal&redirect_uri=http%3A%2F%2Fsome.domain.com%2Fregportal%2Fsso%2Flogin&state=a49a02d5-f873-453f-9148-61793f11ecf3&login=true&scope=openid

We want to replace redirect_uri from "some.domain.com" to "other.domain.com".

How to do it?

Thanks


Solution

You need to do it like this

location /auth/realms/master-realm/protocol/openid-connect/auth {
   if ($args ~* "(.*)(some\.domain\.com)(.*)") {
       set $args "$1other.domain.com$3";
       return 301 $scheme://$host$uri$args;
   }

}

Test:

curl -I  "vm/auth/realms/master-realm/protocol/openid-connect/auth?response_type=code&client_id=regportal&redirect_uri=http%3A%2F%2Fsome.domain.com%2Fregportal%2Fsso%2Flogin&state=a49a02d5-f873-453f-9148-61793f11ecf3&login=true&scope=openid"
HTTP/1.1 301 Moved Permanently
Server: openresty/1.11.2.2
Date: Fri, 15 Sep 2017 06:01:51 GMT
Content-Type: text/html
Content-Length: 191
Connection: keep-alive
Location: http://vm/auth/realms/master-realm/protocol/openid-connect/authresponse_type=code&client_id=regportal&redirect_uri=http%3A%2F%2Fother.domain.com%2Fregportal%2Fsso%2Flogin&state=a49a02d5-f873-453f-9148-61793f11ecf3&login=true&scope=openid


Answered By - Tarun Lalwani
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What should my nginx.conf look like for serving static content

 September 02, 2022     nginx, nginx-reverse-proxy     No comments   

Issue

I have the following content in my nginx.conf and everything else is as is

server {
    listen       8081;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    #location / {
        #root   html;
        #index  index.html index.htm;
    #}

    location = /console {
        proxy_pass http://localhost:7001/main/console;
        proxy_set_header        Host             $host;
        proxy_set_header        X-Real-IP        $remote_addr;
        proxy_set_header        X-Forwarded-For  $proxy_add_x_forwarded_for;
        auth_basic "Admin Area";
        auth_basic_user_file /etc/apache2/.htpasswd;
    }
}

Now when I launch http://localhost:8081/console it successfully launches the webpage and even asks me for password.

But there are some static content in this location /main/resources/org/nett/main/images/jquery-3.1.1.min.js

When I click on this it throws 404. What should be in my nginx.conf to serve the static content inside /main/resources/org/nett/main/images/ folder?


Solution

You'll note that the location of the static content, /main/resources..., doesn't match any of your locations. . resources is not under /main/console, and therefore there's no way to access it under your existing proxy-pass location.

Reconsider whether you need to change the path of your proxy. It can be done, but requires additional configuration. If you merely redirect / to 7001:/, then when the data at /main/console refers to /main/resources, that will also have a valid proxy path through nginx.

If your definition of 'working' means the /console maps to 7001/main/console, you'll have to expand upon that definition to address also how you want to map requests under /main/<anythingelse>, more of which may have yet to be uncovered. You'll also have to handle rewriting the references to itself the application sends back ( if, for example, more is requested from /main/console, it will have the same problem as stuff under /main/resources, because it, too, doesn't match /console. URL rewrites at the proxy should only be undertaken with a decent grasp of regular expressions and http, and only with a sincere and practiced willingness to RTFM. its complicated.

By the by, if you're attempting to add basic auth to whatever's on 7001, make sure to also encrypt your connection (HTTPS), otherwise your credentials are plaintext on the network (http://mark-kirby.co.uk/2013/how-to-authenticate-apis-http-basic-vs-http-digest/).



Answered By - Daniel Farrell
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to config nginx docker container to recognize localhost application in different port?

 September 02, 2022     docker, nginx, nginx-location, nginx-reverse-proxy, node.js     No comments   

Issue

Setup: All following are running on my Mac OS:

localhost:8089 a nodejs REST api runing in my local, OUTSIDE of the nginx container, stand alone!

locahost:80 nginx docker container

I was able to serve static file inside the nginx docker container, but when I set the config for the nginx as:

http {
    server {
        location / {
            root /usr/share/nginx/html;
        }
        location /api/ {
            proxy_pass http://localhost:8089;
        }
    }
}

for some reason, any localhost:80/api call that suppose to direct to http://localhost:8089; call is returning 404 not found page

404 Not Found

nginx/1.13.6

Any idea where is the config I made wrong? I feel like maybe I shouldn't use localhost:8089 inside nginx? But then what should I be using?

An example can be found here https://github.com/adamchenwei/docker-nginx-playground


Solution

Containers have their own networking namespace / networking stack. So localhost inside the container is the localhost of the container itself.

If you are running Docker for Mac, there is a special hostname that's available inside the container that allows you to connect to services that are running on the host itself. Refer to this answer for more information; https://stackoverflow.com/a/43541732/1811501

If you are running Docker on Linux, this answer (on the same question) allows you to find the IP-address to connect to; https://stackoverflow.com/a/31328031/1811501



Answered By - thaJeztah
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to configure nginx as reverse proxy to different nginx running on different subnet with uWSGI?

 September 02, 2022     nginx, nginx-reverse-proxy, uwsgi     No comments   

Issue

This is one step ahead of this article,

Below is the current flow and configuration and it is working. I can access UI from /16 machine. This was done by someone else. I guess by following above article.

Client------------------nginx----------------------nginx
192.168.13.90/16   eth0 - 192.168.13.2/16   eth0   - 192.168.13.9/16
                                            eth0.1 - 182.28.129.202/24
                                                     |
                                                     |
                                                   uWSGI

I am beginner to nginx and python. I am trying to configure nginx as reverse proxy on eth0.1 interface in the following scenario,

Client------------------nginx---------------------nginx
182.28.129.201/24  eth0 - 192.168.13.9/16   eth0 - 192.168.13.2/16
                   eth0.1 - 182.28.129.202/24
                                                    |
                                                    |
                                                  uWSGI

Below are the current nginx config files with my current trial & error comments,

Edit2 - Comment out the location block for special login.html page from upstream nginx reverse proxy server

# /etc/nginx/nginx.conf
# 192.168.13.2/16  - this upstream server

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;
    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    access_log /var/log/access.log;
    error_log /var/log/error.log;

    gzip on;
    gzip_disable "msie6";

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Below is the ui.conf file included by above nginx.conf, # /etc/nginx/sites-enabled/ui.conf

# 192.168.13.2/16  -  this upstream server

server {
    listen 192.168.13.2:80;
    server_name 192.168.13.2:80;

    access_log /var/log/access.log;
    error_log /var/log/error.log;

    # No physical login.html,
    #  it is passing it to root which is login screen
    #location = /login.html {                          <--------- Edit2
    #   return 301 /;
    #}

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/run/ui.sock;
    }
}

Following is the nginx.conf on eth0.1 on different subnet,

Edit1 - The problem I am facing with this config is the request is proxied to the upstream nginx server but the response is gzip and chunked. I don't see page loading on the client.

Edit2 - I added location block for special page login.html and it loaded the page but it stuck at the redirect page. See wireshark stream below,

# /etc/nginx/nginx.conf

# eth0   - 192.168.13.9/16
# eth0.1 - 182.28.129.202/24  - Reverse proxy

user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log debug;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  0;   #Disable

    gzip  on;
    gzip_disable    "msie6";                          #   <----------- Edit2

    server {
        listen          182.28.129.202:8080;
        server_name     182.28.129.202:8080;

        #rewrite        ^(.*) $scheme://$server_name$1 permanent;

        location = /login.html {                       #   <---------- Edit2
            proxy_pass              http://192.168.13.2:80/;
        }

        location / {
            proxy_pass              http://192.168.13.2:80;

            #  trial and error
            #proxy_http_version     1.1;
            #proxy_set_header       Host $host;
            #proxy_set_header       X-Real-IP $remote_addr;
            #proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;
            #proxy_set_header       X-Forwarded-Proto http;
            #proxy_bind             192.168.13.9;
            #proxy_buffering        off;
        }
    }
}

Edit2 - Wireshark stream, stuck at redirect page, /home

POST /login.html HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://182.28.129.202:8080/login.html
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: 182.28.129.202:8080
Content-Length: 33
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache

password=xxxxxxxxxx&login-submit=Server: nginx/1.6.2
Date: Thu, 07 Dec 2017 20:10:50 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 239
Connection: close
Location: http://192.168.13.2/home
Set-Cookie: remember_token=admin|c8aa43aab8b27724a207eb28ac7d1034d1e274fc4f528002a2d6106bb7c36a41756f6951d518f632d426a7d8c8257ad00dbab78e3daf7a5bbbc723ba33107e5e; Expires=Fri, 07-Dec-2018 20:10:50 GMT; Path=/
Set-Cookie: session=.eJw1zksKwzAMRdG9eNyBLUeSnc0E2ZJoBgkln1Hp3msonT4uvPMOix92PsN8Hbc9wrJqmAMgdgOPWhJx06jSM-lEuUKN5CzelFJJJY-pRs5QDLkgRWsdPZZkTZETkRikws1gUufeRL0a9zhlHAlXFEDPYlLHW1RI3sAYwoC87Nhkt_360-7Tjh9PdFv38PkC4lY3Tg.DQsxyg.lZrpSNvXnwE-JHT5t6qlYLAQP4Y; Expires=Sun, 07-Jan-2018 20:10:50 GMT; HttpOnly; Path=/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="/home">/home</a>.  If not click the link.

First I am trying to be able to access UI over HTTP and then with HTTPS. I am not able to move ahead due to my knowledge in this area so greatly appreciate any guidance.

Thank you,


Solution

I was doing a lot of trial and error and thats where was observing weird errors. Following are the config files which worked for me. Hope it will help some-one.

# 192.168.13.2/16  -  this upstream server

server {
    listen 192.168.13.2:80;
    server_name 192.168.13.2:80;

    access_log /var/log/access.log;
    error_log /var/log/error.log;

    # No physical login.html,
    #  it is passing it to root which is login screen
    location = /login.html {
       rewrite ^ http://192.168.13.2/ last;
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/var/run/ui.sock;
    }
}

# /etc/nginx/nginx.conf

# eth0   - 192.168.13.9/16
# eth0.1 - 182.28.129.202/24  - Reverse proxy

user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log debug;

pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  0;   #Disable

    gzip  on;
    gzip_disable    "msie6";

    server {
        listen          182.28.129.202:8080;
        server_name     182.28.129.202:8080;

        location / {
            proxy_buffering     off;
            proxy_set_header    Host $http_host;
            proxy_set_header    X-Real-IP $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto http;
            proxy_pass          http://192.168.13.2:80;
        }
    }
}


Answered By - eyePatch
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I set Host as $upstream_addr in Nginx

 September 02, 2022     nginx, nginx-location, nginx-reverse-proxy     No comments   

Issue

I have the following config below on Nginx.conf

<b>
http {
    log_format my_upstream '$remote_addr [$time_local] "$request" $status'
        '"$upstream_addr" $upstream_response_time $upstream_http_etag $host $http_host';
    access_log /var/log/nginx/upstream.log my_upstream;

upstream myapp{
         ip_hash;
         server x.x.x.174:8001;
         server x.x.x.96:8001;
     }

    server {
     listen 9000;
     #websocket
     location /jms {
         proxy_pass http://myapp/jms;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "Upgrade";
         proxy_set_header Host $upstream_addr;
     }

     location / {
        proxy_pass http://myapp;
     }
     }
}
</b>

I tried setting the Host to $upstream_addr, but unfortunately, I'm receiving null in the request. Could anyone please help me in setting up the Host as $upstream_addr. Thanks, Bhaskar.


Solution

As Larry mentioned, the request headers (and body) are fixed before the upstream is selected. Hence your $upstream_addr would always return null.

What you can do is add two levels of proxy. But this might get messy if you have a lot of upstreams of myapp.

upstream myapp{
     ip_hash;
     server x.x.x.174:8001;
     server x.x.x.96:8001;
 }

upstream main {
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
}
server {
  listen      8001 ;

  location / {
    proxy_pass       http://x.x.x.174:8001/jms;
    proxy_set_header Host x.x.x.174:8001;
  }
}

server {
  listen      8002 ;
  location / {
     proxy_pass       http://x.x.x.96:8001/jms;
     proxy_set_header Host x.x.x.96:8001;
  }
}

server {
listen 9000;
#websocket
location /jms {
     proxy_pass http://main;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
}

location / {
    proxy_pass http://myapp;
}
}


Answered By - Aakash Agarwal
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make ngnix docker containers accessible through proxy?

 September 02, 2022     docker, docker-compose, nginx, nginx-reverse-proxy     No comments   

Issue

Let's say I have three docker containers with nginx. Their exposed port is mapped to 8080, 8181 and 8282 respectively. I want to configure the server on 8080 that it proxies /example01 and /example02 to the other two applications. This is my config file:

server {

    listen 80;
    server_name  localhost;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://localhost:8181/;
    }

    location /example02 {
        proxy_pass http://localhost:8282/;
    }
}

So if I run the containers, each of the applications are accessible (http://localhost:8080, http://localhost:8181 and http://localhost:8282).

Now, I don't really get why http://localhost:8080/example01 and http://localhost:8080/example02 are not redirecting correctly. Instead I get a 502 bad gateway error. Does it have something to do with my exposed ports and the VIRTUAL_PORT?

Thanks in advance.


Solution

This is because of the container network scope. Those container's localhost's are inside each container respectively - and that's not where your ports are mapped to. Instead do:

$ ifconfig

on your host machine and find your local ip address and proxy the traffic to your host - that has the ports mapped.

conf:

server {

    listen 80;
    server_name  localhost;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://192.168.1.2:8181/;
    }

    location /example02 {
        proxy_pass http://192.168.1.2:8282/;
    }
}

where 192.168.1.2 is your own machine local ip address.

Another way would be to link those containers and not proxy via localhost - but the alias you'd provide in the link definition. I can elaborate if you choose this method.

-- edit with the linking method --

In order to have your services linked, you need to use a docker tool docker-compose. Assuming you're familiar with what it is ( doc refs on the bottom ), you could write a compose file like this:

first-nginx:
   build: first-nginx/
   ports:
      - 8080:80
   links:
      - second-nginx
      - third-nginx

second-nginx:
   build: second-nginx/
   ports:
      - 8081:80

third-nginx:
   build: third-nginx/
   ports:
      - 8082:80

Placed in your project's root directory like this:

root
  - first-nginx
    + nginx.conf
    + Dockerfile
    + some-other.files
  - second-nginx
    + some.files
    + another-nginx.conf
    + Dockerfile
  - third-nginx
    + some-nginx.conf
    + Dockerfile
  + docker-compose.yml

And you'd configure the "main" nginx to utilize the created links like so:

conf:

server {

    listen 80;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://second-nginx/;
    }

    location /example02 {
        proxy_pass http://third-nginx/;
    }
}

Be sure to ask if anything is unclear.

links ref

compose ref



Answered By - trust512
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to prevent 502 status code as response by haproxy as load balancer

 September 02, 2022     bad-gateway, failover, haproxy, kestrel, nginx-reverse-proxy     No comments   

Issue

I have 3 server:

server (A)= a nginx(port 80) as reverse proxy to kestler (5000 port)
server (B)= a nginx(port 80) as reverse proxy to kestler (5000 port)
server (C)= a HAProxy as load balancer for port 80 of server (A) and (B)
and server A & B are quite similar.

every things works very well and haproxy forwards requests to server (A) & (B), but if kestrel in one of servers (e.g. A) be killed, nginx respond 502 bad gateway error and haproxy not detect this issue and still redirect requests to it, and this is mistake! it must redirect requests to server (B) in this time.

global
    log 127.0.0.1 local2 info
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    log global
    mode http
    option httplog
    option dontlognull
    option redispatch
    retries 3
    timeout connect 5s
    timeout client 50s
    timeout server 50s
    stats enable
    stats hide-version
    stats auth admin:admin
    stats refresh 10s
    stats uri /stat?stats

frontend http_front
    bind *:80
    mode http
    option httpclose
    option forwardfor
    reqadd X-Forwarded-Proto:\ http
    default_backend http_back

backend http_back
    balance roundrobin
    mode http
    cookie SERVERID insert indirect nocache
    server ServerA 192.168.1.2:80 check cookie ServerA
    server ServerB 192.168.1.3:80 check cookie ServerB

How Can I resolve this issue? thanks very much.


Solution

You are only checking whether nginx is running, not whether the application is healthy enough to use.

In the backend, add option httpchk.

option httpchk GET /some/path HTTP/1.1\r\nHost:\ example.com

Replace some path with a path that will prove whether the application is usable on that server if it returns 200 OK (or any 2xx or 3xx response), and replace example.com with the HTTP Host header the application expects.

option httpchk

By default, server health checks only consist in trying to establish a TCP connection. When option httpchk is specified, a complete HTTP request is sent once the TCP connection is established, and responses 2xx and 3xx are considered valid, while all other ones indicate a server failure, including the lack of any response.

This will mark the server as unhealthy if the app is not healthy, so HAProxy will stop sending traffic to it. You will want to configure a check interval for each server using inter and downinter and fastinter options on each server entey to specify how often HAProxy should perform the check.



Answered By - Michael - sqlbot
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to configure nginx to support signalr3 under cloudflare?

 September 02, 2022     asp.net, nginx, nginx-reverse-proxy, signalr     No comments   

Issue

I am struggling with signalr3 and nginx reverse proxy configuration, my nginx cfg looks like this:

server {
listen       80;
server_name  my.customdomain.com;

location / {
  root /pages/my.customdomain.com;
  index index.html index.htm;
  try_files $uri $uri/ /index.html =404;
}

## send request back to kestrel ##
location /proxy/ {
 proxy_pass  http://xxxxxxxxxx.westeurope.cloudapp.azure.com/;

 proxy_set_header        Host            $host;
 proxy_set_header        X-Real-IP       $remote_addr;
 proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
 }
}

What do I miss here?

When I browse my page, I receive OK for

GET /proxy/notifications/negotiate 

and

GET /proxy/notifications?id=uFQtMDg1dXib6LGvUssQhQ

but 404 for POST

POST proxy/notifications?id=uFQtMDg1dXib6LGvUssQhQ

pls halp!

ps. my Hub is very simple...

[AllowAnonymous]
public class NotificationHub : Hub
{

}

Solution

This is a websocket based app so you need additional nginx config

location / { 
    proxy_set_header X-Real-IP $remote_addr; 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header X-NginX-Proxy true; 
    #proxy_set_header X-Forwarded-Proto https; 
    proxy_pass 127.0.0.1:8080; 
    proxy_set_header Upgrade $http_upgrade; 
    proxy_set_header Connection "upgrade";
    proxy_ssl_session_reuse off; 
    proxy_set_header Host $http_host; 
    proxy_cache_bypass $http_upgrade; 
    proxy_redirect off; 
}


Answered By - Tarun Lalwani
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use NGINX to forward the request to Docker Microservice

 September 02, 2022     docker, nginx, nginx-location, nginx-reverse-proxy     No comments   

Issue

I wanted to use NGINX as a reverse proxy to forward the request to microservices. Both NGINX and Microservices are hosted on docker container.

Below is my nginx.conf file

    worker_processes 1;

    events { worker_connections 1024; }

    #test

    http {

        sendfile on;

        # upstream docker-nginx {
        #     server nginx:80;
        # }

        upstream admin-portal {
            # server admin-portal:9006;
            server xx.xx.xx.xx:9006;
            # server localhost:9006;

        }

server {
            listen 8080;

            location / {
                proxy_pass         http://admin-portal;
                proxy_redirect     off;
                proxy_set_header   Host $host;
                proxy_set_header   X-Real-IP $remote_addr;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Host $server_name;
            }


        }


    }

Dockerfile

FROM nginx
RUN apt-get update && apt-get install -y \
curl 
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 8080

docker-compose.yml

version: '3'
services:
  nginx:
    restart: always
    build: ../../conf/
    volumes:
    - ./mysite.template:/etc/nginx/conf.d/mysite.template
    ports:
    - "8080:8080"
    networks:
      - cloud


networks:
  cloud:
   driver: bridge
  • I am able to access nginx home page by localhost:8080
  • admin-portal is a microservice running on 9006 port

But if I do localhost:8080/admin-portal/ I am getting below error

nginx_1 | 2018/07/04 07:08:17 [error] 7#7: *1 "/usr/share/nginx/html/admin-portal/index.html" is not found (2: No such file or directory), client: xx.xx.xx.xx, server: your-domain.com, request: "GET /admin-portal/ HTTP/1.1", host: "xx.xx.xx.xx:8080" nginx_1 | 2018/07/04 07:08:17 [error] 7#7: *1 open() "/usr/share/nginx/html/404.html" failed (2: No such file or directory), client: xx.xx.xx.xx, server: your-domain.com, request: "GET /admin-portal/ HTTP/1.1", host: "xx.xx.xx.xx:8080" nginx_1 | xx.xx.xx.xx - - [04/Jul/2018:07:08:17 +0000] "GET /admin-portal/ HTTP/1.1" 404 170 "-" "curl/7.47.0" admin-portal/

Please suggest what changes I need to do to forward the request to admin-portal using nginx


Solution

upstream admin-portal {
    server 127.0.0.1:9006;
}

it should be :

upstream admin-portal {
    server 172.17.0.1:9006;
}

With 172.17.0.1 is ip address gateway of containers.

Or docker inspect containermicroservice_id then get ip address of that container.

 upstream admin-portal {
    server ipaddressofmicroservicecontainer:9006;
}

Put ip address of server into

        server_name    localhost ipaddressofserver www.example.com;

then access http://ipaddressofserver:8080/admin-portal

Comment out this part:

#server {
#            listen       8080;
#            server_name     your-domain.com www.your-domain.com;
#            root   /usr/share/nginx/html;
#            index  index.html index.htm;

#            error_page  404              /404.html;
#            error_page   500 502 503 504  /50x.html;
#            location = /50x.html {
#                root   html;
#            }
        }


Answered By - Thanh Nguyen Van
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to configure NGINX Location for Multiple Service

 September 02, 2022     docker, docker-machine, nginx, nginx-location, nginx-reverse-proxy     No comments   

Issue

I want to configure NGINX to work as a reverse proxy to other Microservices.

I am able to forward the request from NGINX to one of the microservice

if I do curl http://xx.xx.xx.xx:8080/ call did landed on consumer-portal But its using default location configuration /

when I comment the 1st block and configure the same code for location /consumer-portal and do curl http://xx.xx.xx.xx:8080/consumer-portal

I get :

Cannot GET /consumer-portal

I have more than 10 microservice which I want to call using NGINX.

Below is my nginx.conf file

worker_processes 4;
events { 
        worker_connections 1024; 
    }

http {
    sendfile on;
    upstream consumer-portal {

         server xx.xx.xx.xx:9006;

    }
    upstream publisher-portal {

         server xx.xx.xx.xx:9001;
    }
    server {
        listen 8080;

        #1st Block
        #location / {
        #    proxy_pass         http://consumer-portal;
        #    proxy_redirect     off;
        #    proxy_set_header   Host $host;
        #    proxy_set_header   X-Real-IP $remote_addr;
        #    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        #    proxy_set_header   X-Forwarded-Host $server_name;
        #}

        #2nd Block
        location  /consumer-portal {
            proxy_pass         http://consumer-portal;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

        #3rd Block
        location /publisher-portal/ {
             proxy_pass         http://publisher-portal;
             proxy_redirect     off;
             proxy_set_header   Host $host;
             proxy_set_header   X-Real-IP $remote_addr;
             proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header   X-Forwarded-Host $server_name;
         }
}
}

Also, Please let me know If I can forward the request using docker container name.

e.g instead of server xx.xx.xx.xx:9006 i want to use server consumer-portal:9006

Please suggest what changes I need to do into .conf file.


Solution

    location  /consumer-portal {
        proxy_pass         http://consumer-portal;

If your proxy_pass URL is just a domain/IP/hostname and has no URI set then Nginx will pass the full client request URL to the proxy for requests matching the location block. So here your request to

http://xx.xx.xx.xx:8080/consumer-portal will be proxied by Nginx to

http://consumer-portal/consumer-portal

If your proxy_pass URL is a domain/IP/hostname which also has a URI appended then Nginx will replace the matching part of your location block from the original client request with the URI in your directive and then proxy the resulting URL to the upstream server. So if you had proxy_pass http://consumer-portal/new/location; then a request to

http://xx.xx.xx.xx:8080/consumer-portal/account would be proxied by Nginx to

http://consumer-portal/new/location/account

As you want to remove /consumer-portal from the request to the upstream proxy the solution is as simple as adding a trailing slash to your proxy_pass directive, like this:

proxy_pass http://consumer-portal/;



Answered By - miknik
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to configure a container with Apache for Drupal 8 behind another container Nginx used as a reverse proxy

 September 02, 2022     apache2.4, docker, drupal-8, nginx-reverse-proxy     No comments   

Issue

We have set up a reverse-proxy Nginx to redirect the requests to the right web service container.

Config Nginx reverse-proxy :

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name weblab.mhf.mhc;
    client_max_body_size 200M;

    location /client_portal/ {
        resolver 127.0.0.11 ipv6=off;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://client_portal;
        access_log /var/log/nginx/client_portal.access.log;
        error_log /var/log/nginx/client_portal.error.log;
    }
}

The website client_portal is hosted by another container using Apache as web server.

Config Apache client_portal :

<VirtualHost *:80>
    ServerAdmin toto@toto.com
    ServerName weblab.mhf.mhc
    DocumentRoot /srv/www/
    ErrorLog ${APACHE_LOG_DIR}/client_portal.error.log
    CustomLog ${APACHE_LOG_DIR}/client_portal.access.log combined
    <Location "/client_portal">
        AllowOverride All
        Require all granted
    </Location>
</VirtualHost>

When I navigate to https://weblab.mhf.mhc/client_portal the front page is loading correctly with this config but the redirections are broken. If i go to https://weblab.mhf.mhc/client_portal/user/login I get a 404 error. I also tried this configuration (used in production) but the front page is not loading correctly (all css/ js files are broken) :

<VirtualHost *:80>
    ServerAdmin toto@toto.com
    ServerName weblab.mhf.mhc
    DocumentRoot /srv/www/
    ErrorLog ${APACHE_LOG_DIR}/client_portal.error.log
    CustomLog ${APACHE_LOG_DIR}/client_portal.access.log combined

    <Directory  /srv/www/client_portal>
        Options -Indexes +Includes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

I have tried to switch apache to nginx and used the official drupal 8 configuration for nginx (https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/) but I have the same problem. What is wrong in the configuration please ?


Solution

Finally, I found the error.

I had to use this configuration :

<VirtualHost *:80>
    ServerAdmin toto@toto.com
    ServerName weblab.mhf.mhc
    DocumentRoot /srv/www/
    ErrorLog ${APACHE_LOG_DIR}/client_portal.error.log
    CustomLog ${APACHE_LOG_DIR}/client_portal.access.log combined

    <Directory  /srv/www/client_portal>
        Options -Indexes +Includes +FollowSymLinks -MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

For Drupal the MultiViews option has to be disable :

If the Apache server has Options +MultiViews enabled by default, then the Apache >Virtualhost configuration should also contain Options -MultiViews (or have -MultiViews >added to the existing Options directive).

source : https://www.drupal.org/docs/8/system-requirements/web-server



Answered By - V1v13n
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to run a ASP.NET Core Web API dll file as a service in Nginx server?

 September 02, 2022     .net, asp.net-core, asp.net-core-webapi, nginx-reverse-proxy, ubuntu     No comments   

Issue

I have an AWS EC2 instance running on Ubuntu 16.04 server. I am running an ASP.NET Core Web API server in this instance.

I have followed this link to host ASP.NET Core on Linux with Nginx. I have followed the tutorial until the Monitoring the app section. Now, i have run the web api dll file using below command and it is listening at http://localhost:5000

dotnet MyWebAPI.dll

I have run this above command by connecting with the EC2 instance using PuTTY. As i have set up the reverse proxy server, so i can hit my endpoint nicely using postman.

But, when i close the PuTTY session, the dll file is not running anymore. As a result, i could not hit the endpoint.

So, what should i do to keep the dll file running on localhost as a service so that it does not stop when i close the PuTTY session?


Solution

I could run my application as a service inside the Nginx server. Now, if i close the PuTTY session, the service is still running. I have used systemd to create a service file to start and monitor the underlying web app.

systemd is an init system that provides many powerful features for starting, stopping, and managing processes.

At first, i have created a service file for my web application

sudo nano /etc/systemd/system/my-web-api.service

Then, inside that my-web-api.service file, i have included below configurations:

[Unit] 
Description=My first .NET Core application on Ubuntu 

[Service] 
WorkingDirectory=/home/ubuntu/MyWebAPI 
ExecStart=/usr/bin/dotnet /home/ubuntu/MyWebAPI/MyWebAPI.dll 
Restart=always 
RestartSec=10 # Restart service after 10 seconds if dotnet service crashes 
SyslogIdentifier=offershare-web-app
Environment=ASPNETCORE_ENVIRONMENT=Production 

[Install] 
WantedBy=multi-user.target

Then, i need to enable the service and run it.

sudo systemctl enable my-web-api.service
sudo systemctl start my-web-api.service
sudo systemctl status my-web-api.service

Now, the status command should show the service as running if the configuration is correct. Now, my web application is running, kestrel by default listens on port 5000, so my application is available on http://localhost:5000.

Now, if i close the PuTTY session, my web api is still running.



Answered By - Setu Kumar Basak
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Proxy Pass from / to /index.html

 September 02, 2022     nginx, nginx-location, nginx-reverse-proxy     No comments   

Issue

I'm currently working on a JS Project, that uses the url path. Now if I go on my website with example.com/, the JavaScript won't work, because I actually need example.com/index.html.

I'm already using an reverse proxy to proxy pass to two different docker containers. So my idea was to pass the request to example.com/index.html when example.com/ is called. But I can't figure out the regex stuff to achieve this goal.

My old config:

server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location / {
    proxy_pass http://structure.example:80;
}

location /cdn {
    proxy_pass http://content.example:80;
}

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

}

Stuff I tried:

    server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location / {
    proxy_pass http://structure.nocms:80/index.html;
}

location ~* \S+ {
    proxy_pass http://structure.nocms:80;
}

location /cdn {
    proxy_pass http://content.nocms:80;
}



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

}

Solution

Below config should work for you

server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location = / {
    rewrite ^ /index.html permanent;
}

location / {
    proxy_pass http://structure.example:80;
}

location /cdn {
    proxy_pass http://content.example:80;
}

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

}


Answered By - Tarun Lalwani
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to add the 'upstream try' to the request which I send to the backend server

 September 02, 2022     nginx, nginx-config, nginx-reverse-proxy     No comments   

Issue

I have an nginx server which acts as a load balancer.

The nginx is configured to upstream 3 tries: proxy_next_upstream_tries 3

I am looking for a way to pass to the backend server the current try number of this request - i.e. first, second or last.

I believe it can be done by passing this data in the header, however, how can I configure this in nginx and where can I take this data from?

Thanks


Solution

I sent this question to Nginx support and they provided me this explanation:

As long as you are using proxy_next_upstream mechanism for retries, what you are trying to do is not possible. The request which is sent to next servers is completely identical to the one sent to the first server nginx tries - or, more precisely, this is the same request, created once and then sent to different upstream servers as needed. If you want to know on the backend if it is handling the first request or it processes a retry request after an error, a working option would be to switch proxy_next_upstream off, and instead retry requests on 502/504 errors using the error_page directive.
See http://nginx.org/r/error_page for examples on how to use error_page.

So, I did as they advised me:

proxy_intercept_errors on;

location / {
     proxy_pass http://example.com;
     proxy_set_header NlbRetriesCount 0;
     error_page 502 404 @fallback;
}

location @fallback {
     proxy_pass http://example.com;
     proxy_set_header NlbRetriesCount 1;
}


Answered By - Gal S
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to get url parameter and pass to proxy_pass using nginx

 September 02, 2022     nginx, nginx-config, nginx-reverse-proxy     No comments   

Issue

I need to get the parameter from an URL, for example, abc=MY_STRING:

https://my-address/test?abc=MY_STRING

And at the reverse proxy (my-address), is configured like this:

location /test?(.*) {
  proxy_pass http://local-server:1234/test?$args
}

but it is not working.

I tried another configuration:

location /test?(.*) {
  proxy_pass http://local-server:1234/test?$1
}

but not worked too.


Solution

You cannot match the query string part of the URI with a location or rewrite statement, as it is not part of the normalized URI.

But you don't need to. The URI (complete with query string) will be passed upstream unless you redirect it using a rewrite or try_files statement.

For example:

location /test {
    proxy_pass http://localhost:1234;
}

The URI /test?abc=MY_STRING will match the location and be passed to localhost:1234 exactly the same. See this document for more.



Answered By - Richard Smith
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing