{{tag>nginx faq route alias}}

====== Nginx - Вопросы и Ответы ======

  * [[http://mailman.nginx.org/pipermail/nginx-ru/|Архив рассылки]]
  * [[http://forum.nginx.org/list.php?21|Форум]]


===== Вопросы-Ответы =====

==== Q: Надо перенаправить с site.com на www.site.com ====

<code nginx>
server {
    listen	80;
    server_name site.com;
    return      301 http://www.site.com$request_uri;
}

server {
    listen       80;
    server_name  www.site.com;
}
</code>

==== Q: Надо перенаправить на другую папку ====

    * location /d { rewrite ^ other-folder permanent; } 

==== Q: Надо перенаправить GET на другой сервер ====

    * <code>
location /d { 
  rewrite ^ http://server.ru$request_uri? permanent; #301 redirect 
}
</code>

==== Q: Надо перенаправить GET|POST на другой сервер ====

    * В данном случае необходимо просто проксировать запрос
    * <code nginx>
location ~* /d {  
  proxy_pass http://new-server.ru:80; 
  proxy_redirect  http://new-server.ru:80 /; 
  resolver 8.8.8.8; 
  break; 
}
</code>

==== *Q: Надо переправить в другой location, используя ошибку ====

  * <code nginx>
location @nocached {
}
location / {
  if ($cookie_dle_user_id) { return 412; }
}
error_page 412 = @nocached;
</code>

==== Q: Блокировка IP адресов и подсететей в Nginx ====

  * [[nginx:allow-deny|Блокировка IP адресов и подсететей в Nginx]]
  
  * **Q: Настройка proxy_pass на удаленный домен по DNS**
  * <code nginx>
location ^~ /freegeoip/ {
  #use google as dns
  resolver 8.8.8.8;
  proxy_pass http://freegeoip.net/json/$remote_addr;
}
</code>

==== Q: Как запаролить location в Nginx ====


  * <code nginx>
location ^~ /secure/ {
	root /www/mysite.com/httpdocs/secure;
        auth_basic            "Website development";
        auth_basic_user_file  /www/mysite.com/authfile;	
}
</code> Затем генерируем сам файл, где логин будет admin, а пароль pass <code bash>$ php -r "echo 'admin:'. crypt('pass', base64_encode('pass'));" > /www/mysite.com/authfile</code>

==== Q: Как перенаправить обработку скрипта в другую папку ====

<code nginx>
server {
    listen       80;
    server_name site.com;
    location ^~ /api/target/ {

	index receive.php;

	alias /some/path/to/site/target/;

        location ~ \.php$ {

        	# Fix for server variables that behave differently under nginx/php-fpm than typically expected
        	fastcgi_split_path_info ^(.+\.php)(/.+)$;

        	# Include the standard fastcgi_params file included with nginx
        	include fastcgi_params;

        	fastcgi_param  PATH_INFO        $fastcgi_path_info;
        	fastcgi_index receive.php;

        	# Override the SCRIPT_FILENAME variable set by fastcgi_params
        	fastcgi_param  SCRIPT_FILENAME  $request_filename;

        	# Pass to upstream PHP-FPM; This must match whatever you name your upstream connection
        	fastcgi_pass phpfpm;

        	#fastcgi_ignore_client_abort off;
        	#try_files $uri =404;

        }

    }
}
</code>

==== Q: Как добавить / в конец ====


<code nginx>
rewrite ^([^.\?]*[^/])$ $1/ permanent;
</code>

==== Q: Редирект на страницу ====

<code nginx>
server {
    location = /oldpage.html {
        return 301 http://example.org/newpage.html;
    }
}
</code>

==== Q: Распределение ресурсов между источниками CORS ====

<code nginx>
location ~* .(eot|ttf|woff) { 
    add_header Access-Control-Allow-Origin *; 
}
</code>

==== Q: Как завернуть location на yii appliaction ====

<code nginx>
root /var/www/dev.payments-api.host.org/frontend/web;

    location /admin/ {

        alias /var/www/dev.payments-api.host.org/backend/web/;

        # serve static files direct + allow friendly urls
        # Note: The seemingly weird syntax is due to a long-standing bug in nginx: https://trac.nginx.org/nginx/ticket/97
        try_files $uri $uri/ /admin//admin/index.php?$args;

        location ~ /admin/.+\.php$ {
            include fastcgi_params;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $request_filename;
            include        fastcgi_params;
            fastcgi_read_timeout 300;
            proxy_redirect    off;
        }

    } # / location

    location @admin {
         rewrite ^/admin(/.*)$ /index.php?$1;
    }

</code>

==== Q: Редирект на определенный путь в URI ====

<code nginx>
location /old-site {
    rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;
}
</code>
==== Q: Количество открытых файлов и их лимиты ====

<code bash>
for pid in `pidof nginx`; do echo "$(< /proc/$pid/cmdline)"; egrep 'files|Limit' /proc/$pid/limits; echo "Currently open files: $(ls -1 /proc/$pid/fd | wc -l)"; echo; done
</code>

