A
A
Alexander Lapenko2013-06-26 08:35:41
Nginx
Alexander Lapenko, 2013-06-26 08:35:41

Redirecting Ajax requests using nginx

Good afternoon! I'm trying to organize the creation of 3rd level domains for certain users (user1.site.ru should work like site.ru/user/1). Faced the problem of paths on subdomains (because the links in the project are all relative).
I'm trying to use the web server to determine Ajax requests and redirect them to the usual URL (i.e. user1.site.ru/ajax/123 should work the same as site.ru/ajax/123)

Here is a piece of the config for a specific subdomain (let's say user1)

location / {
      resolver 127.0.0.1;
      if ($http_x_requested_with = XMLHttpRequest) {
        set $pass1 http://www.site.ru/;
      }
      if ($http_x_requested_with != XMLHttpRequest) {
        set $pass1 http://www.site.ru/user/1/;
      }
      proxy_pass $pass1;
    }


Ajax requests are not working correctly.
I ask for help in writing a check for an Ajax request.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mayorovp, 2013-06-26
@mayorovp

Try dropping the if - it doesn't always work in the obvious way. You need something like this:

resolver 127.0.0.1;

location / {
  proxy_pass http://www.site.ru/user/1/;
}

location /ajax/ {
  proxy_pass http://www.site.ru/ajax/
}

Although, do proxy_pass to your own server ...

M
Maxim Timokhin, 2013-06-26
@timokhin

It worked for me like this:

server{
...
if ($http_x_requested_with = XMLHttpRequest) {
    rewrite ^(.*)$ /ajax/$1 last;
}

if inside location, then replace last with break
nginx.org/ru/docs/http/ngx_http_rewrite_module.html

A
Aleksandr Kuznetsov, 2013-06-27
@x_T

nginx.org/ru/docs/http/ngx_http_map_module.html

map $http_x_requested_with $passvar {
    default http://www.site.ru/user/1/;
    XMLHttpRequest http://www.site.ru/;
}

resolver 127.0.0.1;

server {
 location / {
  proxy_pass $passvar;
 }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question