Nginx Snippets. Приемы и советы

Категория: Linux

Сниппеты настроек nginx сервера для сайта.

Пример использования rewrite:

server {
    listen 801;
    server_name blog.domain.lcl;
    root /var/www/blog/public/;

    index index.php index.html index.php;

    location /test {
        ## @note root в контексте location, не применяется при rewrite! Учитывается только server.root
        if (!-e $request_filename) {
            ## @note Перенаправляет на /test2 внутри server.root (меняет URL)
            rewrite ^(.+)$ /test2 last;
        }
    }
}

Gzip сжатие данных:

## Gziped
gzip  on;
gzip_static  on;
gzip_proxied  any;
gzip_types  text/plain text/css text/javascript text/xml application/xml application/json application/javascript application/x-javascript application/xml+rss image/svg+xml;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_disable "MSIE [1-6]\.";

Настройка CORS:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET,HEAD,POST,PUT,DELETE,OPTIONS';
add_header Access-Control-Allow-Headers 'Auth-Token,Content-Type';

Отдавать статику:

## Serve static assets directly
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ {
    access_log off;
    expires max;
    log_not_found off;
}

Удалить двойные слеши:

## Clean double slashes
if ($request_uri ~* //) {
    rewrite ^/(.*) /$1 permanent;
}

Страницы HTTP ошибок:

error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /usr/share/nginx/html;
}

Множественные if-условия (лайфхак):

    if ($server_port = 80) { set $UD "A"; }
    if ($host ~* teambox.com) { set $UD  "${UD}B"; } 
    if ($http_cookie !~* "auth_token") { set $UD  "${UD}C"; } 
    if ($http_accept ~* "image/") { set $UD "${UD}D"; }
    
    if ($UD = ABCD) {
      proxy_pass http://host.com; 
      break; 
    } 

#nginx #snippets #config #hack #multiple conditions #sites #webserver

категория: Linux