PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, June 24, 2022

[FIXED] How to write Nginx Config file to pass URL with id ([0-9]+) to perform Load Balancing

 June 24, 2022     express, load-balancing, nginx, reverse-proxy     No comments   

Issue

suppose I have to go to an URL localhost/tag/9 where 9 is an id.So what do I need to write inside

location /tag/? {

}

The thing is actually I have several tags(links) in a webpage and each tag has an id associated with them.When I click on a tag having id 9,It takes me to localhost/tag/9 and I get 404 error.Now I want to know how to proxy_pass this URL to my actual URL which is localhost:1111/tag/9 ? My express app is running on port 1111 and 2222 and 3333.

My conf file so far

upstream expressweb {
    server localhost:1111;
    server localhost:2222;
    server localhost:3333;
}
server {

    listen 80;
    location /my_app/ {
        proxy_pass http://expressweb/;
    }
    location /tag/[0-9]+/ {
        proxy_pass http://expressweb/tag/$1/;
    }
}

Any idea how can i do it?

Edit:

I have tried doing

location /tag/1/ {
        proxy_pass http://expressweb/tag/1/;
    }
    location /tag/2/ {
        proxy_pass http://expressweb/tag/2/;
    }
    location /tag/3/ {
        proxy_pass http://expressweb/tag/3/;
    }

and so and its working fine.But I am still struggling to write it with regex.

Solved it

writing the regex part as such did the work for me.One thing to note here is that any regex must be wrapped up by () in nginx config file.And the $ at the end indicates the regex values will be at the end of an URL

 location ~ /([1-9][0-9]*)$ {
        proxy_pass http://expressweb/tag/$1/;
    }

Solution

nginx serves files, not tags in a webpage - that can mean multiple things to start with.

Provided that the page your nginx serves as you suggest references a file located at http://expressweb/tag/9 (and you can get it with curl from the host nginx runs at), you can proxy-pass simply observing correct syntax. From the top of my head

location /tag { proxy_pass http://expressweb; }

Or if you really need regex

location ~ /tag/([0-9]+) { prxy_pass http://expressweb/tag/$1; }

Here is proxy_pass syntax



Answered By - wick
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

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
Comments
Atom
Comments

Copyright © PHPFixing