
我是 nginx 重寫引擎的新手。我正在嘗試將舊的 htaccess 檔案轉換為 nginx 的格式,但遇到了一些麻煩。
# ------------------------------------------------------ #
# This redirects index.php to / #
# ------------------------------------------------------ #
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(index|index\.php)\ HTTP/
RewriteRule ^(index|index\.php)$ http://domain.com/ [R=301,L]
# ------------------------------------------------------ #
# This rewrites 'directories' to their PHP files, #
# fixes trailing-slash issues, and redirects .php #
# to 'directory' to avoid duplicate content. #
# ------------------------------------------------------ #
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*)/$ http://twitstamp.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^.]+\.php\ HTTP/
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^.]+)\.php$ http://twitstamp.com/$1 [R=301,L]
# ------------------------------------------------------ #
# If it wasn't redirected previously and is not #
# a file on the server, rewrite to image #
# ------------------------------------------------------ #
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9_\-@#\ "'\+]+)/?([a-z0-9_\-]+)?(\.png|/)?$ generation/image.php?user=${escapemap:$1}&template=${escapemap:$2} [NC,L]
那是我的 htaccess 檔案。現在這是我到目前為止所得到的...
# ------------------------------------------------------ #
# This redirects index.php to / #
# ------------------------------------------------------ #
if ($request_uri ~* "^/index.php\??$") {
rewrite ^.*$ http://$host? permanent;
}
# ------------------------------------------------------ #
# This rewrites 'directories' to their PHP files, #
# fixes trailing-slash issues, and redirects .php #
# to 'directory' to avoid duplicate content. #
# ------------------------------------------------------ #
if (!-e $request_filename) {
rewrite ^(.*)$ $1.php;
last;
}
# ------------------------------------------------------ #
# If it wasn't redirected previously and is not #
# a file on the server, rewrite to image #
# ------------------------------------------------------ #
if (!-e $request_filename) {
rewrite ^([a-z0-9_\-@#\ "'\+]+)/?([a-z0-9_\-]+)?(\.png|/)?$ generation/image.php?user=$1&template=$2;
break;
}
index.php 重定向工作正常,“目錄”名稱 -> php 檔案重定向也是如此。但是,我不知道如何做幾件事:實施尾部斜杠修復,並從外部重定向 .php 文件,以便我沒有任何重複的文件。我希望所有頁面看起來都很乾淨,例如/help、/about等。另外,我無法獲得圖像的重寫規則。我想要任何不是真實文件或目錄(-e 標誌)並且不是可重寫文件(如 /about)的內容重定向到生成/等...
答案1
你的做法是錯誤的。 Nginx 喜歡位置區塊,例如將 /index.php 重定向到 / 你會做的。
location = /index.php {
rewrite ^ http://domain.com/$args permanent;
}
您還需要查看 try_files。一般來說,如果你在 Nginx 中使用 if,那麼你很可能做錯了。
我建議閱讀本文,了解 Nginx 如何使用伺服器區塊和位置區塊的基本介紹:http://blog.martinfjordvald.com/2010/07/nginx-primer/