如何在沒有擴展名的情況下訪問我的.html或.php檔案?
這是我的檔案夾結構:
C:\Apache24\htdocs\search-html\test
search-html
test
low.html
high.html
new.html
我的網址是 127.0.0.1/search-html/test/low.html
但我想像這樣訪問這個 URL 127.0.0.1/search-html/test/low
為了運行本地主機服務器,我httpd.exe -k在命令提示符下使用start
uj5u.com熱心網友回復:
您可以將.htaccess檔案添加到檔案根目錄以重寫 url。
# Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options FollowSymLinks
RewriteEngine On
RewriteBase /
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.] )/$ $1.php
# Remove .html-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^([^\.] )/$ $1.html
# End of Apache Rewrite Rules
</IfModule>
如果你想在末尾添加一個斜杠,你可以添加這個位。
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
uj5u.com熱心網友回復:
在您的.htaccess檔案中使用以下內容。.htaccess檔案所在的位置并不重要,只要它位于檔案根目錄內以及所請求的檔案路徑中的某處。
如果您正在請求表單的 URL,http://127.0.0.1/search-html/test/low則C:\Apache24\htdocs是您的DocumentRoot(查看您的“檔案夾結構”),如服務器配置中所定義。
RewriteEngine On
# Append ".html" extension if the file exists
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.html [L]
# Otherwise append ".php" extension if the file exists
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.php [L]
上述規則明確排除了任何已經包含類似檔案擴展名的 URL。所以靜態資源(圖片、JS 和 CSS 等)自然會被排除在外。
或者,如果您什么都不做.htaccess并且想要無擴展名的 URL,那么只需啟用 MultiViews。例如:
Options MultiViews
但是,這確實有一些警告:
- 擴展名的網址上基本上是啟用的一切,不只是
.html和.php檔案。包括圖片、JS 和 CSS 等。 - 如果您以后想使用 mod_rewrite 進行更復雜的 URL 重寫,那么您可能需要禁用MultiViews 并改用 mod_rewrite 解決方案。MultiViews 和 mod_rewrite 可能會導致意外沖突。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358464.html
上一篇:除特定檔案夾外,強制尾隨斜杠
下一篇:將外部/api/entity/1URL重寫為內部/api/entity.php/1(或/api/entity.php?id=1)的通用方法
