2014-10-20 143 views
0

因此,我似乎可以找到其中一些解決方案,但無法讓所有人一起工作。我想要做的是從各個方面創建乾淨的URL。乾淨的URL www。刪除index.php,刪除.php擴展,使用HTACCESS添加尾部斜槓

  1. 解決所有WWW。和非www。到非www。頁面
  2. 刪除index.php文件中出現的所有(即,如果導航到文件夾/blog/index.php解決AS /博客/)的所有URL
  3. 刪除PHP擴展(即/page.php到/頁/)
  4. 加斜槓(即/頁面/頁/)

這是我到目前爲止有:

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule .*[^/]$ %{REQUEST_URI}/ [L,R=301] 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.+)/$ $1.php [L] 

這完成了清潔的URL刪除php擴展並增加尾部斜槓。我必須取出www.to non和刪除index.php,因爲乾淨的URL和尾部斜槓停止工作。謝謝大家。

+0

您確定這些網址仍然可以這樣工作嗎?看起來你想將用戶從'../ page.php'重定向到'../ page /',但Apache會知道在哪裏尋找'../ page /'? – Rudie 2014-10-20 22:44:18

回答

1

這是你的.htaccess應該是什麼樣子:

RewriteEngine On 

# Remove www. 
<IfModule mod_rewrite.c> 
    RewriteCond %{HTTPS} !=on 
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] 
    RewriteRule^http://%1%{REQUEST_URI} [R=301,L] 
</IfModule> 

# Remove file extensions, add a trailing slash. 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^([^/]+)/$ $1.php 
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$ 
RewriteRule (.*)$ /$1/ [R=301,L] 

This大約是往返的URL刪除的文件擴展名一個很好的參考文章。請記住,爲此,您必須在所有鏈接中引用非擴展版本,例如<a href="about">About</a>,而不是<a href="about.php">About</a>

當你在做.htaccess的事情,我也可以建議添加下面的代碼片段。前兩個關注網站速度,第二個關注自定義404頁面,第三個關注強制UTF-8(因此您不必在HTML中聲明它)。

# Expires caching (Caching static files for longer drastically improves performance, you might even want to put even more aggressive times) 
<IfModule mod_expires.c> 
ExpiresActive On 
ExpiresByType image/jpg "access 1 year" 
ExpiresByType image/jpeg "access 1 year" 
ExpiresByType image/gif "access 1 year" 
ExpiresByType image/png "access 1 year" 
ExpiresByType text/css "access 1 month" 
ExpiresByType text/html "access 1 month" 
ExpiresByType text/x-javascript "access 1 month" 
ExpiresByType image/x-icon "access 1 year" 
ExpiresDefault "access 1 month" 
</IfModule> 

# Gzip 
<ifmodule mod_deflate.c> 
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript 
</ifmodule> 

# 404 Page 
ErrorDocument 404 /404.php 

# Force UTF-8 
AddDefaultCharset utf-8 

I wrote about this在CodePen博客文章,如果你有興趣。

HTML BP有一個瘋狂的700+行的.htaccess,你可以看到一些很酷的技巧。

+0

爲什麼部分在'IfModule'中而部分不是? – Rudie 2014-10-20 22:43:22

+0

我想你可以把它放在'IfModule'中,我只是沒有。 – Tim 2014-10-20 22:45:34

+0

它的部分原因在於'IfModule'是因爲我從[HTML BP](https://github.com/h5bp/html5-boilerplate/blob/master/dist/.htaccess)取得了這部分內容(它具有'IfModule's中的所有內容),並且我寫了另一部分。而我從來沒有改變它,我永遠使用相同的'.htaccess'。 – Tim 2014-10-20 22:52:06

相關問題