2014-04-01 156 views
0

重定向我在example.com子域和nginx的

server { 
    listen 8082; ## listen for ipv4; this line is default and implied 
    #listen [::]:80 default ipv6only=on; ## listen for ipv6 

    server_name example.com; 

與我的博客的設置,並從WWW重定向。到非www我也有這個塊:

server { 
    listen  8082; 
    server_name www.example.com; 
    return   301 http://example.com$request_uri; 
} 

這也適用,但後來我想添加一個子域:「api.example.com」。首先,我嘗試在站點中添加另一個文件,並啓用符合鏈接的站點。但是這沒有奏效,第二個文件根本沒有觸發。

接下來,我將子域添加爲第一個文件中的服務器塊。這工作。但現在每個子域都會導致api.example.com。

首先,我不明白怎麼 「test.example.com」 可能導致這個serverblock:

server { 
    listen 8082; ## listen for ipv4; this line is default and implied 
    #listen [::]:80 default ipv6only=on; ## listen for ipv6 

    server_name api.example.com; 
} 

因爲服務器名是API .example.com的,並且test.example.com是另一種子域。我怎麼讓每個子域沒有指定導致主頁或自定義錯誤頁面?

+0

在我添加最後一個塊之前,無論我輸入哪個子域,重定向塊都會被踢入。 – andeersg

+0

所以你在'/ sites-enabled /'文件夾中有兩個文件(鏈接)? –

+0

不,現在所有3個服務器塊都在一個文件中,唯一一個活動。 – andeersg

回答

1

首先,要將您的3個域/子域服務器塊分隔爲三個不同的文件,可能是更好的組織實踐。據我所知,你的nginx被配置爲從啓用網站的地方讀取.conf文件。創建從啓用網站到網站的鏈接的可能性只是讓您在不需要刪除配置文件的情況下輕鬆禁用子域/子域(只需刪除符號鏈接)即可。這很好。但是你的配置可能有問題。你可以嘗試,從這個樣品nginx.conf(source):

# Generic startup file. 
user {user} {group}; 

#ususally equal to number of CPU's you have. run command "grep processor /proc/cpuinfo | wc -l" to find it 
worker_processes 2; 

error_log /var/log/nginx/error.log; 
pid  /var/run/nginx.pid; 

# Keeps the logs free of messages about not being able to bind(). 
#daemon  off; 

events { 
    worker_connections 1024; 
} 

http { 
# rewrite_log on; 

    include mime.types; 
    default_type  application/octet-stream; 
    access_log   /var/log/nginx/access.log; 
    sendfile   on; 
# tcp_nopush   on; 
    keepalive_timeout 3; 
# tcp_nodelay  on; 
# gzip    on; 
     #php max upload limit cannot be larger than this  
    client_max_body_size 13m; 
    index    index.php index.html index.htm; 

    # Upstream to abstract backend connection(s) for PHP. 
    upstream php { 
       #this should match value of "listen" directive in php-fpm pool 
     server unix:/tmp/php-fpm.sock; 
#  server 127.0.0.1:9000; 
    } 

    include sites-enabled/*; 
} 

如果你不想/需要改變你的所有nginx.conf文件,只需看看最後一行(一個包含) 。

然後,只需在啓用網站的位置創建您的每個服務器(vhost)配置文件。

關於配置子域名的問題,請驗證您是否正在爲子域名創建相應的DNS條目。這是顯而易見的,但請仔細檢查它,因爲您的nginx配置似乎是正確的。相比之下,使用不同的文件創建服務器塊:

server { 
    listen 8082; ## listen for ipv4; this line is default and implied 
    #listen [::]:80 default ipv6only=on; ## listen for ipv6 

    server_name api.example.com; 
    #the rest of your server config goes here. 

} 
+0

我不確定這個DNS部分,但我的域名指向我的服務器,所以這部分工作。 nginx服務器塊的順序是否重要? – andeersg

+0

如果您的終端上運行「ping subdomain.domain.com」時,您的服務器IP爲響應,那麼它就沒有問題。 順序無關緊要。但是當你使用外部的conf文件時,就沒有順序,只有一些「服務器虛擬主機」的外部文件。請使用我答案中的建議。我已經使用nginx將近3年了,並且我總是按照我的建議配置子域 - 所以我可以確認這將完全按照您的要求進行。 ;) – bazaglia

+0

我遵循你的例子,現在它與多個文件一起工作,唯一不起作用的是,如果我去「test.example.com」或其他任何事情,nginx顯示api.example.com文件。我可以創建* .example.com嗎?它會採取任何東西,但指定的子域名? – andeersg