0

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?

2 Answers 2

1

I was able to get it done like this:

if ( $uri ~ "^/play$" ) {
 rewrite (.*)  /;
}
if ( $uri ~ "^/play/([0-9A-Za-z]*)$" ) {
  rewrite ^/play/([0-9A-Za-z]*)$ /?ref=$1;
}
0

You shouldn't use if here. The correct way to implement these kinds of things in nginx are location blocks. For example:

location ~ /profile/(.+)$ {
    rewrite ^ /p=$1 break;
}

location ~ /play/(.+)$ {
    rewrite ^ /v=$1 break;
}

Here we match the paths with location directives, capture the part after directory into a variable, and use that with the redirect.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .