I'm currently using nginx rewrites to pass server variables. I'm able to pass a variable like this: http://example.com/test
such that it passes that as: http://example.com/?p=test
. I do that with this:
location / {
rewrite ^/([^/\.]+)$ /?p=$1 break;
}
Now I want to be able to pass variables using subdirectories so that mappings occur like this:
http://example.com/profile/user1
=> http://example.com/?p=user1
and I want to have multiple rules like this so that on the same site I also have a rule like:
http://example.com/play/vid1
=> http://example.com/?v=vid1
I tried this but it didn't work:
location /profile/ {
rewrite ^/([^/\.]+)$ /?p=$1 break;
}
location /play/ {
rewrite ^/([^/\.]+)$ /?v=$1 break;
}
I also tried without the trailing slashes like:
location /profile {
rewrite ^/([^/\.]+)$ /?p=$1 break;
}
location /play {
rewrite ^/([^/\.]+)$ /?v=$1 break;
}
How can I do this?
I was able to get it done like this:
You shouldn't use
if
here. The correct way to implement these kinds of things in nginx arelocation
blocks. For example:Here we match the paths with
location
directives, capture the part after directory into a variable, and use that with the redirect.