Apache 學習筆記 - 使用mod_rewrite進行URL重定向和重新映射(Using mod_rewrite for redirection and remapping of URLs)

http://httpd.apache.org/docs/2.4/en/rewrite/remapping.html

使用mod_rewrite重定向和重映射(Redirecting and Remapping with mod_rewrite)

This document supplements the mod_rewrite reference documentation. It describes how you can use mod_rewrite to redirect and remap request. This includes many examples of common uses of mod_rewrite, including detailed descriptions of how each works.

本文件是mod_rewrite 對參考文件的補充。它描述瞭如何使用mod_rewrite重定向和重新映射請求。這包括mod_rewrite常用用法的很多例子,包括每個工作原理的詳細描述。

Note that many of these examples won’t work unchanged in your particular server configuration, so it’s important that you understand them, rather than merely cutting and pasting the examples into your configuration.

請注意,這些示例中的很多不會在特定的服務器配置中保持不變,因此重要的是要了解它們,而不是僅將示例剪切並粘貼到配置中。

從舊到新(內部) From Old to New (internal)

Description:
Assume we have recently renamed the page foo.html to bar.html and now want to provide the old URL for backward compatibility. However, we want that users of the old URL even not recognize that the pages was renamed - that is, we don’t want the address to change in their browser.

假設我們最近將 foo.htm重命名爲bar.html,並且現在想要提供舊的URL以實現向後兼容。但是,我們希望用戶不知道網頁已重命名 - 也就是說,我們不希望地址在其瀏覽器中更改。

Solution:
We rewrite the old URL to the new one internally via the following rule:

我們通過以下規則在內部重新編寫舊的URL:

RewriteEngine  on
RewriteRule    "^/foo\.html$"  "/bar.html" [PT]

重寫從舊到新(外部)Rewriting From Old to New (external)

Description:
Assume again that we have recently renamed the page foo.html to bar.html and now want to provide the old URL for backward compatibility. But this time we want that the users of the old URL get hinted to the new one, i.e. their browsers Location field should change, too.

再假設我們最近將 foo.htm重命名爲bar.html,並且想要提供舊的URL以實現向後兼容。但是這次我們希望給用戶暗示新的網址,即他們的瀏覽器Location也應該改變。

Solution:
We force a HTTP redirect to the new URL which leads to a change of the browsers and thus the users view:

我們強制HTTP重定向到新的URL,導致瀏覽器發生更改,因此用戶查看:

RewriteEngine  on
RewriteRule    "^/foo\.html$"  "bar.html"  [R]

Discussion
In this example, as contrasted to the internal example above, we can simply use the Redirect directive. mod_rewrite was used in that earlier example in order to hide the redirect from the client:

在這個例子中,與上面的內部例子相比,我們可以簡單地使用Redirect指令。在前面的例子中使用了mod_rewrite來隱藏來自客戶端的重定向:

Redirect "/foo.html" "/bar.html"

資源移動到另一臺服務器(Resource Moved to Another Server)

Description:
If a resource has moved to another server, you may wish to have URLs continue to work for a time on the old server while people update their bookmarks.

如果某個資源已移至其他服務器,您可能希望舊版服務器上的網址繼續運行一段時間,同時人們更新其書籤。

Solution:
You can use mod_rewrite to redirect these URLs to the new server, but you might also consider using the Redirect or
RedirectMatch directive.

您可以使用mod_rewrite將這些URL重定向到新服務器,但您也可以考慮使用Redirect或RedirectMatch指令。

#With mod_rewrite
RewriteEngine on
RewriteRule   "^/docs/(.+)"  "http://new.example.com/docs/$1"  [R,L]
#With RedirectMatch
RedirectMatch "^/docs/(.*)" "http://new.example.com/docs/$1"
#With Redirect
Redirect "/docs/" "http://new.example.com/docs/"

從靜態到動態(From Static to Dynamic)

Description:
How can we transform a static page foo.html into a dynamic variant foo.cgi in a seamless way, i.e. without notice by the browser/user.

我們如何能夠以無縫的方式將靜態頁面 foo.html轉換爲動態變體 foo.cgi,即無需瀏覽器/用戶注意。

Solution:
We just rewrite the URL to the CGI-script and force the handler to be cgi-script so that it is executed as a CGI program. This way a request to /~quux/foo.html internally leads to the invocation of /~quux/foo.cgi.

我們只需將URL重寫爲CGI腳本,並強制該處理程序爲CGI腳本,以便它作爲CGI程序執行。這樣一個/~quux/foo.html 內部導致調用的請求/~quux/foo.cgi。

RewriteEngine  on
RewriteBase    "/~quux/"
RewriteRule    "^foo\.html$"  "foo.cgi"  [H=cgi-script]

向後兼容性文件擴展名更改(Backward Compatibility for file extension change)

Description:
How can we make URLs backward compatible (still existing virtually) after migrating document.YYYY to document.XXXX, e.g. after translating a bunch of .html files to .php?

在將document.YYYY移植到document.XXXX後,我們如何使URL向後兼容(虛擬地存在),例如在將一堆.html文件翻譯爲.php之後?

Solution:
We rewrite the name to its basename and test for existence of the new extension. If it exists, we take that name, else we rewrite the URL to its original state.

我們將該名稱重寫爲其基本名稱並測試新擴展的是否存在。如果它存在,我們將採用該名稱,否則我們將URL重寫爲其原始狀態。

#   backward compatibility ruleset for 向後兼容性規則集
#   rewriting document.html to document.php
#   when and only when document.php exists
<Directory "/var/www/htdocs">
    RewriteEngine on
    RewriteBase "/var/www/htdocs"

    RewriteCond "$1.php" -f
    RewriteCond "$1.html" !-f
    RewriteRule "^(.*).html$" "$1.php"
</Directory>

Discussion
This example uses an often-overlooked feature of mod_rewrite, by taking advantage of the order of execution of the ruleset. In particular, mod_rewrite evaluates the left-hand-side of the RewriteRule before it evaluates the RewriteCond directives. Consequently, $1 is already defined by the time the RewriteCond directives are evaluated. This allows us to test for the existence of the original (document.html) and target (document.php) files using the same base filename.

通過利用規則集的執行順序,本示例使用了mod_rewrite的一個經常被忽略的特性。特別是,在評估RewriteCond指令之前,mod_rewrite會評估RewriteRule的左側。因此,在評估RewriteCond指令時已經定義了$ 1。這使我們可以使用相同的基本文件名來測試原始(document.html)和目標(document.php)文件的存在。

This ruleset is designed to use in a per-directory context (In a <Directory> block or in a .htaccess file), so that the -f checks are looking at the correct directory path. You may need to set a RewriteBase directive to specify the directory base that you’re working in.

此規則集旨在用於每個目錄上下文(在<Directory>塊或.htaccess文件中),以便 -f 檢查查看正確的目錄路徑。您可能需要設置RewriteBase指令來指定您所在的目錄庫。

規範主機名稱(Canonical Hostnames)

Description:
The goal of this rule is to force the use of a particular hostname, in preference to other hostnames which may be used to reach the same site. For example, if you wish to force the use of www.example.com instead of example.com, you might use a variant of the following recipe.

此規則的目標是強制使用特定的主機名,而不是其他可用於訪問同一站點的主機名。例如,如果您希望強制使用www.example.com而不是 example.com,則可以使用以下配方的變體。

Solution:
The very best way to solve this doesn’t involve mod_rewrite at all, but rather uses the Redirect directive placed in a virtual host for the non-canonical hostname(s).

解決這個問題的最好方法根本不涉及mod_rewrite,而是使用Redirect 放置在虛擬主機中的非指定主機名的指令。

<VirtualHost *:80>
  ServerName undesired.example.com
  ServerAlias example.com notthis.example.com

  Redirect "/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
  ServerName www.example.com
</VirtualHost>

You can alternatively accomplish this using the <If> directive:
您也可以使用該<If> 指令來完成此操作 :

<If "%{HTTP_HOST} != 'www.example.com'">
    Redirect "/" "http://www.example.com/"
</If>

Or, for example, to redirect a portion of your site to HTTPS, you might do the following:
或者,例如,要將網站的一部分重定向到HTTPS,您可以執行以下操作:

<If "%{SERVER_PROTOCOL} != 'HTTPS'">
    Redirect "/admin/" "https://www.example.com/admin/"
</If>

If, for whatever reason, you still want to use mod_rewrite - if, for example, you need this to work with a larger set of RewriteRules - you might use one of the recipes below.
如果無論出於何種原因,您仍然想使用mod_rewrite - 例如,您需要使用更大的一套RewriteRules - 您可以使用下面的一個配方。

For sites running on a port other than 80:
對於在80以外的端口上運行的站點:

RewriteCond "%{HTTP_HOST}"   "!^www\.example\.com" [NC]
RewriteCond "%{HTTP_HOST}"   "!^$"
RewriteCond "%{SERVER_PORT}" "!^80$"
RewriteRule "^/?(.*)"        "http://www.example.com:%{SERVER_PORT}/$1" [L,R,NE]

And for a site running on port 80
對於在80端口上運行的站點

RewriteCond "%{HTTP_HOST}"   "!^www\.example\.com" [NC]
RewriteCond "%{HTTP_HOST}"   "!^$"
RewriteRule "^/?(.*)"        "http://www.example.com/$1" [L,R,NE]

If you wanted to do this generically for all domain names - that is, if you want to redirect example.com to www.example.com for all possible values of example.com, you could use the following recipe:

如果您想爲所有域名一般做到這一點-那就是,如果你想重定向example.com到 www.example.com的所有可能的值 example.com,你可以使用下面的方法:

RewriteCond "%{HTTP_HOST}" "!^www\." [NC]
RewriteCond "%{HTTP_HOST}" "!^$"
RewriteRule "^/?(.*)"      "http://www.%{HTTP_HOST}/$1" [L,R,NE]

These rulesets will work either in your main server configuration file, or in a .htaccess file placed in the DocumentRoot of the server.
這些規則集既可以在您的主服務器配置文件中,也可以在.htaccess放置在DocumentRoot服務器中的文件中使用。

在多個目錄中搜索頁面(Search for pages in more than one directory)

Description:
A particular resource might exist in one of several places, and we want to look in those places for the resource when it is requested. Perhaps we’ve recently rearranged our directory structure, dividing content into several locations.

某個特定資源可能存在於其中一個地方,我們希望在請求時在這些地方查找資源。也許我們最近重新安排了我們的目錄結構,將內容分成幾個位置。

Solution:
The following ruleset searches in two directories to find the resource, and, if not finding it in either place, will attempt to just serve it out of the location requested.

以下規則集在兩個目錄中搜索以查找資源,如果在任一位置都找不到,將嘗試從請求的位置出來。

RewriteEngine on

#   first try to find it in dir1/...
#   ...and if found stop and be happy:
RewriteCond         "%{DOCUMENT_ROOT}/dir1/%{REQUEST_URI}"  -f
RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/dir1/$1"  [L]

#   second try to find it in dir2/...
#   ...and if found stop and be happy:
RewriteCond         "%{DOCUMENT_ROOT}/dir2/%{REQUEST_URI}"  -f
RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/dir2/$1"  [L]

#   else go on for other Alias or ScriptAlias directives,
#   etc.
RewriteRule   "^"  "-"  [PT]

重定向到地理分佈式服務器(Redirecting to Geographically Distributed Servers)

Description:
We have numerous mirrors of our website, and want to redirect people to the one that is located in the country where they are located.

我們網站上有許多鏡像,並希望將用戶重定向到位於所在國家/地區的用戶。

Solution:
Looking at the hostname of the requesting client, we determine which country they are coming from. If we can’t do a lookup on their IP address, we fall back to a default server.
查看請求客戶的主機名,我們確定他們來自哪個國家。如果我們無法查詢他們的IP地址,我們會回到默認服務器。

We’ll use a RewriteMap directive to build a list of servers that we wish to use.
我們將使用RewriteMap 指令來構建我們希望使用的服務器列表。

HostnameLookups on
RewriteEngine on
RewriteMap    multiplex         "txt:/path/to/map.mirrors"
RewriteCond   "%{REMOTE_HOST}"  "([a-z]+)$" [NC]
RewriteRule   "^/(.*)$"  "${multiplex:%1|http://www.example.com/}$1"  [R,L]
## map.mirrors -- Multiplexing Map

de http://www.example.de/
uk http://www.example.uk/
com http://www.example.com/
##EOF##

Discussion
This ruleset relies on HostNameLookups being set on, which can be a significant performance hit.
這個規則集依賴於 HostNameLookups 被設置on,這可能是一個重大的性能影響。

The RewriteCond directive captures the last portion of the hostname of the requesting client - the country code - and the following RewriteRule uses that value to look up the appropriate mirror host in the map file.
該RewriteCond 指令捕獲請求客戶端的主機名的最後一部分 - 國家代碼 - 並且以下RewriteRule使用該值在映射文件中查找適當的鏡像主機。

瀏覽器依賴內容(Browser Dependent Content)

Description:
We wish to provide different content based on the browser, or user-agent, which is requesting the content.
我們希望基於瀏覽器或用戶代理,其請求的內容上,以提供不同的內容。

Solution:
We have to decide, based on the HTTP header “User-Agent”, which content to serve. The following config does the following: If the HTTP header “User-Agent” contains “Mozilla/3”, the page foo.html is rewritten to foo.NS.html and the rewriting stops. If the browser is “Lynx” or “Mozilla” of version 1 or 2, the URL becomes foo.20.html. All other browsers receive page foo.32.html. This is done with the following ruleset:

我們必須根據HTTP頭“User-Agent”決定要提供哪些內容。以下配置會執行以下操作:如果HTTP頭“User-Agent”包含“Mozilla / 3”,則頁面foo.html 被重寫foo.NS.html並停止重寫。如果瀏覽器是版本1或2的“Lynx”或“Mozilla”,則URL將變爲foo.20.html。所有其他瀏覽器都會收到頁面foo.32.html。這是通過以下規則集完成的:

RewriteCond "%{HTTP_USER_AGENT}"  "^Mozilla/3.*"
RewriteRule "^foo\.html$"         "foo.NS.html"          [L]

RewriteCond "%{HTTP_USER_AGENT}"  "^Lynx/" [OR]
RewriteCond "%{HTTP_USER_AGENT}"  "^Mozilla/[12]"
RewriteRule "^foo\.html$"         "foo.20.html"          [L]

RewriteRule "^foo\.html$"         "foo.32.html"          [L]

規範網址(Canonical URLs)

Description:
On some webservers there is more than one URL for a resource. Usually there are canonical URLs (which are be actually used and distributed) and those which are just shortcuts, internal ones, and so on. Independent of which URL the user supplied with the request, they should finally see the canonical one in their browser address bar.

在一些Web服務器上,有多個URL用於資源。通常有規範的URL(實際使用和分發)以及那些只是快捷方式,內部的URL等等。獨立於用戶提供請求的URL,他們最終應該在瀏覽器地址欄中看到規範的URL。

Solution:
We do an external HTTP redirect for all non-canonical URLs to fix them in the location view of the Browser and for all subsequent requests. In the example ruleset below we replace /puppies and /canines by the canonical /dogs.

我們對所有非規範URL進行外部HTTP重定向,以將其修復到瀏覽器的位置視圖以及所有後續請求中。在下面的示例規則集中,我們用規範/dogs替換/puppies 和/canines 。

RewriteRule   "^/(puppies|canines)/(.*)"    "/dogs/$2"  [R]

Discussion:
This should really be accomplished with Redirect or RedirectMatch directives:
這應該通過重定向或RedirectMatch指令來實現:

RedirectMatch "^/(puppies|canines)/(.*)" "/dogs/$2"

移動 DocumentRoot(Moved DocumentRoot)

Description:
Usually the DocumentRoot of the webserver directly relates to the URL “/”. But often this data is not really of top-level priority. For example, you may wish for visitors, on first entering a site, to go to a particular subdirectory /about/. This may be accomplished using the following ruleset:

通常DocumentRoot ,網絡服務器直接與URL“ /”相關。但通常這些數據並不是真正的最高優先級。例如,您可能希望訪問者在首次進入某個網站時轉到特定的子目錄/about/。這可以使用以下規則集來完成:

Solution:
We redirect the URL / to /about/:
我們將URL重定向/到 /about/:

RewriteEngine on
RewriteRule   "^/$"  "/about/"  [R]

Note that this can also be handled using the RedirectMatch directive:
請注意,這也可以使用RedirectMatch指令處理:

RedirectMatch "^/$" "http://example.com/about/"

Note also that the example rewrites only the root URL. That is, it rewrites a request for http://example.com/, but not a request for http://example.com/page.html. If you have in fact changed your document root - that is, if all of your content is in fact in that subdirectory, it is greatly preferable to simply change your DocumentRoot directive, or move all of the content up one directory, rather than rewriting URLs.

另請注意,該示例僅重寫根URL。也就是說,它會重寫請求http://example.com/,但不會請求http://example.com/page.html。如果你實際上已經改變了你的文檔根目錄 - 也就是說,如果你的所有內容實際上都在該子目錄中,那麼簡單地改變你的DocumentRoot 指令或者將所有內容移動到一個目錄而不是重寫URL 是非常可取的。

後備資源(Fallback Resource)

Description:
You want a single resource (say, a certain file, like index.php) to handle all requests that come to a particular directory, except those that should go to an existing resource such as an image, or a css file.

你需要一個資源(比如index.php等特定文件)來處理所有到達某個特定目錄的請求,除了那些應該轉到現有資源(如圖像或css文件)的請求。

Solution:
As of version 2.2.16, you should use the FallbackResource directive for this:
從版本2.2.16開始,您應該使用以下FallbackResource指令:

<Directory "/var/www/my_blog">
  FallbackResource "index.php"
</Directory>

However, in earlier versions of Apache, or if your needs are more complicated than this, you can use a variation of the following rewrite set to accomplish the same thing:
但是,在較早版本的Apache中,或者如果您的需求比這更復雜,則可以使用以下重寫集的變體來完成同樣的事情:

<Directory "/var/www/my_blog">
  RewriteBase "/my_blog"

  RewriteCond "/var/www/my_blog/%{REQUEST_FILENAME}" !-f
  RewriteCond "/var/www/my_blog/%{REQUEST_FILENAME}" !-d
  RewriteRule "^" "index.php" [PT]
</Directory>

on the other hand,If you wish to pass the requested URI as a query string argument to index.php, you can replace that RewriteRule with:
另一方面,如果您希望將請求的URI作爲查詢字符串參數傳遞給index.php,則可以將該RewriteRule替換爲:

RewriteRule "(.*)" "index.php?$1" [PT,QSA]

Note that these rulesets can be used in a .htaccess file, as well as in a <Directory> block.
請注意,這些規則集可以在.htaccess 文件中使用,也可以在<Directory>塊中使用。

重寫查詢字符串(Rewrite query string)

Description:
You want to capture a particular value from a query string and either replace it or incorporate it into another component of the URL.
您希望從查詢字符串中捕獲特定值,並將其替換或將其合併到URL的另一個組件中。

Solutions:
Many of the solutions in this section will all use the same condition, which leaves the matched value in the %2 backreference. %1 is the beginining of the query string (up to the key of intererest), and %3 is the remainder. This condition is a bit complex for flexibility and to avoid double ‘&&’ in the substitutions.

本節中的許多解決方案都將使用相同的條件,這會在%2反向引用中留下匹配的值。%1是查詢字符串的開始(直到intererest的關鍵字),並且%3是餘數。這種情況對於靈活性有點複雜,並且在替換中避免雙重’&&’。

  • This solution removes the matching key and value:
    該解決方案刪除了​​匹配鍵和值:
# Remove mykey=???
RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$"
RewriteRule "(.*)" "$1?%1%3"
  • This solution uses the captured value in the URL subsitution, discarding the rest of the original query by appending a ‘?’:
    此解決方案使用URL替換中的捕獲值,通過追加’?’來丟棄原始查詢的其餘部分:
# Copy from query string to PATH_INFO
RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$"
RewriteRule "(.*)" "$1/products/%2/?" [PT]
  • This solution checks the captured value in a subsequent condition:
    該解決方案在後續條件中檢查捕獲的值:
# Capture the value of mykey in the query string
RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$"
RewriteCond "%2" !=not-so-secret-value 
RewriteRule "(.*)" - [F]
  • This solution shows the reverse of the previous ones, copying path components (perhaps PATH_INFO) from the URL into the query string.
    此解決方案顯示了與之前相反的方法,將URL中的路徑組件(可能是PATH_INFO)複製到查詢字符串中。
# The desired URL might be /products/kitchen-sink, and the script expects
# /path?products=kitchen-sink.
RewriteRule "^/?path/([^/]+)/([^/]+)" "/path?$1=$2" [PT]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章