2015-05-05 64 views
0

我正在使用Nginx的PHP項目。以下是我在做/etc/nginx/sites-available/defaultNginx的多域指令

server { 

server_name domain_a.com; 
include /etc/nginx/main.conf; // listen, php directives, etc. 

location ~ (.*)\.php(/|$) { 
    fastcgi_pass php:9000; 
    fastcgi_split_path_info ^(.+\.php)(/.*)$; 
    include fastcgi_params; 
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
    fastcgi_param HTTPS off; 
    } 
} 

server { 

server_name domain_b.com; 
include /etc/nginx/main.conf; 

location ~ (.*)\.php(/|$) { 
    fastcgi_pass php:9000; 
    fastcgi_split_path_info ^(.+\.php)(/.*)$; 
    include fastcgi_params; 
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
    fastcgi_param HTTPS off; 

    // Specific to this domain 
    auth_basic "Authentication"; 
    auth_basic_user_file /etc/nginx/.htpasswd; 
    } 
} 

/etc/nginx/main.conf

listen 80; 
client_max_body_size 5M; 

access_log /var/log/nginx/access.log; 
error_log /var/log/nginx/error.log; 

root /var/www/web; 

我在這段代碼有很多重複的:兩個location塊可以在合併一個用於兩個域。我想我可以使用if語句爲domain_b添加我的特定代碼,但根據文檔,這不是一種推薦方式。http://wiki.nginx.org/IfIsEvil

您知道如何才能尊重DRY概念嗎?

THX,

回答

1

對我來說,我在我的conf創建一個文件夾並將其命名爲includes例如,然後你可以包括這在任何你想要的,例如

# /etc/nginx/includes/php.conf 
location ~ (.*)\.php(/|$) { 
    fastcgi_pass php:9000; 
    fastcgi_split_path_info ^(.+\.php)(/.*)$; 
    include fastcgi_params; 
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
    fastcgi_param HTTPS off; 
} 

然後在你的配置做像這樣

server { 
    server_name domain_a.com; 
    include /etc/nginx/main.conf; // listen, php directives, etc. 
    include /etc/nginx/includes/php.conf; 
} 

server { 
    server_name domain_b.com; 
    include /etc/nginx/main.conf; 
    include /etc/nginx/includes/php.conf; 
    auth_basic "Authentication"; 
    auth_basic_user_file /etc/nginx/.htpasswd; 
    } 
} 
+0

謝謝,我被阻止,因爲我嘗試包括在位置auth_basic指令,但它沒有任何意義 –

+0

什麼你的意思是被封鎖嗎? –

+0

我的意思是根據文檔http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html#auth_basic,我被困在一個問題 –