2017-03-16 57 views
1

我在「/ directory /」裏面有一個網站,以及「/ directory/subdirectory /」裏面的一個特殊變體,它只能被幾個特定的​​IP地址訪問。但是,子目錄是虛擬URL,在本例中,網站代碼仍然位於名爲「目錄」的父目錄中。所以我需要重寫。如何防止在拒絕後重寫

這是我目前Nginx的配置文件中的相關部分:

location /directory { 
    # here are various rewrites for my website 

    location /directory/subdirectory/ { 
     allow 10.0.0.0/8; # example range of IP addresses allowed 
     deny all; # disable access for others 
     rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last; # the website location is still in the parent folder but the PHP code knows this specific version is to be used when the user surfs into subdirectory, which is why there is this rewrite 
    } 

    try_files $uri $uri/ /directory/index.php?q=$uri&$args; 
} 

location ~ \.php$ { 
    fastcgi_split_path_info ^(.+\.php)(/.+)$; 
    fastcgi_pass unix:/var/run/php5-fpm.sock; 
    fastcgi_index index.php; 
    include fastcgi.conf; 
    fastcgi_read_timeout 43200; 
} 

我所面臨的問題:我不知道如何儘快停止執行爲「拒絕所有」命中。如果你瀏覽子目錄,不管你的IP是否被上面的指令允許,重寫都會執行。所以有人用一個不允許的IP地址瀏覽子目錄可以看到子目錄內的網站,這當然不是我想要的。如果我註釋掉重寫,那麼允許/拒絕指令按照它們應該的那樣工作。

所以:我怎樣才能指定這個重寫只有在訪問者沒有被拒絕時才被執行? 嘗試添加「error_page 403/403.html;」在「否認所有」之後到達那個位置;指令,但它只會更改403頁(並且只能在評論子目錄中的重寫規則時再次看到)。在搜索網絡已經有好幾天的搜索條件下發生這種情況,並且一直在擺弄着配置的變化,但無濟於事。

此外:一旦我瀏覽到子目錄中的URL,以「.php」結尾,「拒絕全部」不再有效。我認爲這是因爲「location〜.php $」指令,因爲某些原因而優先於上面的嵌套位置指令。我可以解決這個做:

location ^~ /directory/subdirectory/ { 
    allow 10.0.0.0/8; # example range of IP addresses allowed 
    deny all; # disable access for others 
    rewrite ^/directory/subdirectory/(.*)$ /directory/$1 last; 
} 

location /directory { 
    # here are various rewrites for my website 

    try_files $uri $uri/ /directory/index.php?q=$uri&$args; 
} 

location ~ \.php$ { 
    fastcgi_split_path_info ^(.+\.php)(/.+)$; 
    fastcgi_pass unix:/var/run/php5-fpm.sock; 
    fastcgi_index index.php; 
    include fastcgi.conf; 
    fastcgi_read_timeout 43200; 
} 

現在的「位置^〜/目錄/子目錄/」指令在「位置〜.PHP $」獲得優先權指令,這使得「拒絕所有」的工作,但我不知道這是否應該走,因爲它看起來並不像是最清晰的解讀方案,因爲我從「目錄/」位置移出某個位置塊。而且,這仍然不能解決我的主要問題(只對最後的「rewrite ^/directory /子目錄/(.*)$/directory/ $ 1」執行;「爲允許的IP地址執行,而不是那些被拒絕的」拒絕「 。所有的」

謝謝

回答

1

你正面臨着是關係到優先級/順序nginx的處理它的指令,這個問題的詳細解釋,可以發現here (hats off to the author!)

在其執行命令階段後讀取,服務器重寫, find-config,rewrite,post-rewrite,preaccess,access,post-access, 嘗試文件,內容和最後的日誌

由於「重寫」在「訪問」之前,「重寫」指令首先被處理。

因爲「如果」,在「改寫」相以及被處理,一個可以寫:

location ~ \.php$ { 
if ($remote_addr != "172.17.0.1") { 
    return 403; 
} 
rewrite^/your-redirect last; 
}