2

I wish that every request in the following format: /files/(whatever..)/(1 or 2 or 3) will go to the files_1 upstream with the /(whatevet) command. If the url is in the following format /files/(whatever..)/(4 or 5 or 6), it will go to the files_2 upstream with the /(whatevet) command.

Here is my location file:

location ~ "^/files/(.*)/[123]/" { rewrite ^/files/(.*)/(.*) /$1 break; proxy_pass http://files_1 ; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; } location ~ "^/files/(.*)/[456]/" { rewrite ^/files/(.*)/(.*) /$1 break; proxy_pass http://files_2 ; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; } 

When I check the logs, It doesn't do the redirection with the command /files/save/2/ (which should go to files_1 upstream with the command: /save)

How can I do it?

2
  • Your location regex requires a trailing / after the final numeric element. So /files/save/2 does not match any of the above location blocks. Also, your rewrite regex is not guaranteed to pick out only the save for the $1. Commented Jan 25, 2016 at 12:50
  • @RichardSmith: its /files/save/2/. I will update the question Commented Jan 25, 2016 at 12:56

1 Answer 1

4

It's possible that you have another location / block that is redirecting /files/save/2 to /files/save/2/ because the former does not match your current location blocks.

You could eliminate the captures on the rewrite by using a named capture in the location regex, like this:

location ~ "^/files(?<command>.+)/[123]/" { rewrite ^ $command break; ... } 

Alternatively, correct the rewrite directive so that only the command is extracted:

rewrite ^/files(.+)/\d/ $1 break; 

or:

rewrite ^/files/([^/]+)/ /$1 break; 
Sign up to request clarification or add additional context in comments.

3 Comments

I try your suggestion, so I did: location ~ "^/files/(.*)/[123]/" { rewrite ^/files(.+)/\d/ $1 break; proxy_pass http://files_1 ; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; } location ~ "^/files/(.*)/[456]/" { rewrite ^/files(.+)/\d/ $1 break; proxy_pass http://files_2 ; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; } and it still doesn't work for me. It send the all command
location ~ "^/files(?<command>.+)/[123]/" { rewrite ^ $command break; ... } Also this suggestion doesn't work. I get 404. Can you help me with this?
I have tested both approaches and I cannot make either fail. I did correct an error in the third one. Are you sure that nginx is being restarted?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.