wiesson
wiesson

Reputation: 6832

nginx rewrite if specific name is included

I would like to rewrite all requests that contain 'xhr.php' to /xhr.php instead of the original path.

The request:

type: "POST",
url: "/system/classes/templates/address/xhr.getAddress.php",
data: vars,
dataType: "html"

Should go to /xhr.php with the path as argument. I tried this:

 rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 last;

However it does not work. Any ideas? My Config looks like this:

location / {
    root  /var/www/http;
    try_files $uri $uri/ index.php /index.php$is_args$args @rewrite;
}

location @rewrite {
    rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 last;
}

Is this basically possible with nginx? Whats wrong here? Thanks :)

//EDIT: I solved it, however it does not look very efficient …

location / {
  root  /var/www/http;
  try_files $uri $uri/ index.php /index.php$is_args$args;
}

if ($request_uri ~ .*/xhr.*) {
   rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 break;
}

Upvotes: 3

Views: 103

Answers (1)

Stefano Falsetto
Stefano Falsetto

Reputation: 572

You can remove the if and let the rewrite at the same level of location. In this way you'll save one regex for each request (the one inside the if).

Actually I think you can remove the location / too:

root /var/www/http;
rewrite ^/(.*)/xhr.(.*)\.php$ /xhr.php?parameter=$1&parameter2=$2 break;
try_files $uri $uri/ index.php /index.php$is_args$args;

Upvotes: 2

Related Questions