我有一個網站組成如下:
index.php
page1.php
page2.php
page3.php
- images
image1.jpg
image2.jpg
- style
style.css
我想寫一個 htaccess 檔案,它可以給我 SEO 友好的 URL。例如:
https://example.com/page2.php應該https://example.com/page2
并且:
https://example.com/page2.php#mytab應該https://example.com/page2#mytab
但我想僅在第一個目錄上應用這些規則,因此可以使用擴展繼續訪問“影像”和“樣式”目錄。
有人可以幫忙嗎?謝謝
uj5u.com熱心網友回復:
您應該已經鏈接到內部 URL 上沒有擴展名的檔案(即,不是)。我還假設您的 URL 不包含點(通常用于分隔檔案擴展名)。
.phphref="/page1"href="/page1.php"如果需要,實施重寫以附加
.php擴展名。這需要靠近根.htaccess檔案的頂部:RewriteEngine On # Internally rewrite extenionless URLs to append ".php" if required # Tests only requests (that do not contain a dot) in the root directory RewriteCond %{DOCUMENT_ROOT}/$1.php -f RewriteRule ^([^./] )$ $1.php [L]RewriteCond(檔案系統檢查)的替代方案:RewriteCond %{REQUEST_FILENAME}.php -f :或者,您可以完全洗掉該
RewriteCond指令以無條件地重寫根中的所有請求(沒有檔案擴展名)以附加.php擴展名。(可選)如果您要更改 URL 結構并
.php從 URL 中洗掉,并且舊 URL 已被搜索引擎索引和/或被第三方鏈接,那么您還需要實施重定向以洗掉.phpSEO 擴展。在上面的指令之后立即添加以下內容
RewriteEngine(在內部重寫之前):# Redirect to remove the `.php` extension inbound requests # Only affects the root directory RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^([^./] )\.php$ /$1 [R=301,L]針對環境變數進行測驗的條件
REDIRECT_STATUS確保我們不會通過以后的重寫重定向已經重寫的請求,從而避免了重定向回圈。注意:首先使用 302(臨時)重定向進行測驗,以避免潛在的快取問題。
或者(而不是#3),為了防止直接訪問
.php檔案并提供 404 Not Found ,然后在RewriteEngine上面的指令之后立即添加以下內容(在內部重寫之前):# Prevent direct access to ".php" file and serve a 404 instead # Only affects the root directory RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteRule ^([^./] )\.php$ - [R=404]
每次發生 404 錯誤時顯示自定義 404 頁面內容的最佳方式是什么?(我不想使用重定向)
在檔案頂部使用以下內容.htaccess,將完整的 URL 路徑傳遞給ErrorDocument指令。
ErrorDocument 404 /error-docs/e404.php
The stated error document is called using an internal subrequest (there is no external redirect).
Note that this should include the .php file extension here - this is entirely invisible to the user.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439370.html
標籤:php 阿帕奇 .htaccess url重写 搜索引擎优化
