2014-01-14 29 views
0

我想寫實現以下目標.htaccess文件:使用htaccess的刪除結尾的斜槓,index.php文件,並仍然使用相對路徑

  • 條斜線的所有URL
  • 結束
  • 下分的index.php
  • 降PHP擴展的一切文件名不是索引
  • 請網址都尾隨數據由index.php文件處理
  • 使用相對URL,不一個鏈接站點根由於htaccess的僅影響的子目錄(/管理如在下面的實施例)

的一些示例網址(URL顯示實際=位置):

  • /管理= /管理/索引.PHP
  • /管理/頁面名= /admin/pagename.php
  • /管理/目錄= /admin/directory/index.php
  • /管理/一/二/ 3 = /admin/index.php在那裏我可以分析$ _ SERVER [「REQUEST_URI」]用PHP得到變量一,二,三

而這裏的上面我所管理的文件夾中爲止。它消除了PHP擴展,同時讓我訪問任何現有的文件,但.PHP後也去掉一切,不刪除尾隨斜線。

RewriteEngine On 

# Redirect php filename externally 
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC] 
RewriteRule^%1 [R=302,L,QSA] 
# change 302 to 301 on live for perm redirect 

# Redirect php filename internally 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*?)/?$ $1.php [L,QSA] 

# Rewrite Admin URLS (after specififcally looking for files) 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule admin/. admin/index.php [L,QSA] 
# index.php looks at $_SERVER['REQUEST_URI'] to decide what to do next 

# No Directory Listings 
Options -Indexes 

我最關心的是能夠包含文件名(.php,。公司,名爲.css,.js文件)中的相對路徑,而不是必須使用絕對路徑,如果我能幫助它。

回答

1

我一般喜歡去與提供路由功能,而不是所有的文件夾/文件的重寫規則噩夢的框架。有跡象表明,很容易支持此PHP框架,如SilexSymfony,或Laravel的轉換,僅舉幾例。

另一個原因是,在應用程序中執行路由比較容易,就是它抽象應用路由從Web服務器的大部分。例如,如果你轉移到Nginx,你將不得不重構所有上述內容。

我的.htaccess可能類似於以下內容:

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    # Redirect to non-trailing slash 
    RewriteRule ^(.*)/$ /$1 [R=301,L] 
    # Block access to "hidden" directories whose names begin with a period. 
    RewriteRule "(^|/)\." - [F] 
    RewriteBase /
    # Redirect requests that have no real file 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule (.*) index.php [QSA,L] 
</IfModule> 
+0

是什麼RewriteBase /怎麼辦? – Michelle

+0

[文檔](http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase)比我更好地解釋它:D –

+0

我正在考慮將所有流量重新路由到index.php並讓它文件解釋所有的URI,但我不確定性能的影響,我敢肯定,這會使文件包含更多的困難。我不知道什麼是最好的。 – Michelle

相關問題