Mod-Rewrite

Apache ModRewrite 從 rewriteCondition 中的 request_uri 剝離部分

  • July 19, 2016

所以基本上我的 html 中有一個連結,domain.com/app/css/build/app-23471942834.css但是在伺服器上文件實際存在於/fs/current/public/css/build/app-23471942834.css. 有沒有辦法檢查文件中是否存在RewriteCondition?問題是我基本上需要/css/build/app-23471942834.css檢查零件,沒有/app. 有沒有辦法在條件下刪除它?

所以我需要:

  • domain.com/app/login重寫為/fs/current/public/login
  • domain.com/app/build/css/app-123523.css重寫為/fs/current/public/build/css/app-123523.css
  • domain.com/app/build/js/app-123523.js重寫為/fs/current/public/build/js/build/app-123523.css

我正在使用 Laravel,所以在我的public目錄中,預設情況下還有另一個.htaccess

<IfModule mod_rewrite.c>
   <IfModule mod_negotiation.c>
       Options -MultiViews
   </IfModule>

   RewriteEngine On

   # Redirect Trailing Slashes If Not A Folder...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)/$ /$1 [L,R=301]

   # Handle Front Controller...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^ index.php [L]

   # Handle Authorization Header
   RewriteCond %{HTTP:Authorization} .
   RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

對不起,但我真的很討厭 htaccess 文件。謝謝你的幫助。

到目前為止我得到了什麼:

RewriteCond %{HTTP_HOST} ^(www.)?domain.de$ [NC]
RewriteCond %{DOCUMENT_ROOT}/fs/current/public/$1 -f
RewriteRule ^app/(.*)$ /fs/current/public/$1 [L]

RewriteCond %{HTTP_HOST} ^(www.)?domain.de$ [NC]
RewriteRule ^app/(.*)$ /fs/current/public/index.php?/$1 [L]

解決方案:

我這樣解決了我的問題:

RewriteCond %{HTTP_HOST} ^(www.)?domain.de$ [NC]
RewriteCond %{REQUEST_URI} \.(css|jpg|gif|png|js|svg)
RewriteRule ^app/(.+)$ /fs/current/public/$1 [L]

所以所有的重寫只適用於 css/jpg/gif/png/js/svg 我認為我之前遇到的問題是 index.php 文件也被腳本重寫了。

嘗試以下操作:

RewriteEngine On
RewriteRule ^/?app/(css/build/app)-\d+(\.css)$ /fs/current/public/$1$2 [L]

不確定您到底在追求什麼,但這會在內部將表單的 URL 重寫domain.com/app/css/build/app-23471942834.css/fs/current/public/css/build/app.css.

如果您需要在重寫之前檢查目標文件是否存在,那麼您可以在之前添加一個條件RewriteRule(儘管我不確定您為什麼需要這樣做,因為無論如何您都會得到 404)。例如:

RewriteCond %{DOCUMENT_ROOT}/fs/current/public/$1$2 -f

**更新#1:**來自評論……

我需要重寫任何不是文件的東西

哦,好吧,這更有意義。您可以將上述RewriteCond指令替換為以下內容:

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule如果請求的 URL與文件系統上的文件匹配,那隻會處理以下替換。

**更新#2:**從更新的問題…

更通用的解決方案,在現有RewriteEngine指令之後,在 .htaccess 中嘗試以下操作:

RewriteCond %{DOCUMENT_ROOT}/fs/current/public/$1 -f
RewriteRule ^app/(.+)$ /fs/current/public/$1 [L]

這只會在文件系統上存在表單<document-root>/fs/current/public/css/build/app-23471942834.css或文件時重寫請求<document-root>/fs/current/public/login

引用自:https://serverfault.com/questions/790460