[英]Rewrite dynamic URL's and delete “.php” extension
我的.htaccess文件有問題。 好吧,我正在嘗試做兩件事; 刪除所有URL的擴展名“ .php”,例如:將“ localhost / about.php”更改為“ localhost / about”或“ localhost / about /”。 並將動態網址:“ localhost / user / index.php?usr = username”重寫為“ localhost / user / username /”或“ localhost / username”。
我已經找到一種可以同時做這兩種事情的方法。 但是,如果我有刪除“ .php”擴展名的代碼,則重寫動態URL的代碼將無法正常工作。 如果我沒有刪除“ .php”擴展名的代碼,則重寫動態url的代碼也可以工作。
這是我嘗試打開個人資料頁面時網站給我的錯誤:
未找到
在此服務器上找不到請求的URL / user / enric。
要么
未找到
在此服務器上找不到請求的URL /user/enric.php。
我能做什么? 這是.htaccess文件的代碼:
<IfModule mod_rewrite.c>
Options -Multiviews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^channels/page/([0-9]+)/?$ channels/index.php?p=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/?$ channels/index.php?o=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/([0-9]+)/?$ channels/index.php?o=$1&p=$2 [L]
# Delete ".php" extension and adds "/"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)/$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]
# User profiles
RewriteRule ^user/([^/]*)/$ /user/index/?usr=$1 [L,R=301]
</IfModule>
解決方案, 林俊恩
<IfModule mod_rewrite.c>
Options -Multiviews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^channels/page/([0-9]+)/?$ channels/index.php?p=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/?$ channels/index.php?o=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/([0-9]+)/?$ channels/index.php?o=$1&p=$2 [L]
# User profiles
RewriteRule ^user/([^/]*)/$ /user/index.php?usr=$1 [L]
# Delete ".php" extension and adds "/"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteCond %{DOCUMENT_ROOT}%1.php -f
RewriteRule (.*)/$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]
</IfModule>
您需要添加一項檢查,以確保在將.php
擴展名添加到請求中時,該php文件確實存在,並且應該在 php擴展名之前將用戶重寫移動:
<IfModule mod_rewrite.c>
Options -Multiviews
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^channels/page/([0-9]+)/?$ channels/index.php?p=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/?$ channels/index.php?o=$1 [L]
RewriteRule ^channels/([_0-9a-z-]+)/([0-9]+)/?$ channels/index.php?o=$1&p=$2 [L]
# User profiles
RewriteRule ^user/([^/]*)/$ /user/index.php?usr=$1 [L]
# Delete ".php" extension and adds "/"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteCond %{DOCUMENT_ROOT}%1.php -f
RewriteRule (.*)/$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]
</IfModule>
您可以通過在線工具(例如http://www.generateit.net/mod-rewrite/index.php)生成htaccess規則
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.