問題描述
htaccess 刪除 .php 擴展名並重寫為 www (htaccess remove .php extension and rewrite to www)
我正在嘗試在位於我的根目錄中的 htaccess 中完成兩件事,並且應該會影響整個網站的所有網頁。我正在使用 Apache 2.4。
1) 將非 www 重寫為 www(這部分目前正在工作)
2) 從 URL 中刪除 .php 擴展名
對於#2,我發現了兩個關於此的線程,但是當嘗試使用#1 中的代碼實現它時,它似乎永遠無法工作。
如何使用 Apache 隱藏 .html 擴展名mod_rewrite
這是我的代碼,第一部分工作正常,但第二部分似乎對我沒有任何作用,因為“.php”仍然顯示在所有 URL 上。
RewriteEngine On
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{REQUEST_FILENAME}.php ‑f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]
我還查看了這個線程和嘗試了以下方法,仍然無法正常工作。
5 .htaccess 重寫:強制 HTTPS、刪除 index.php、刪除 .php、強制 www、強制尾部斜線
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !‑f
RewriteRule ^(.*)\.(?!js|css)([^.]*)$ $1\.php
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
任何幫助將不勝感激。提前致謝。
已更新
這是文件夾結構和 PHP 代碼所在的位置。大多數 php 文件位於根文件夾中,但還有兩個包含 PHP 代碼的附加文件夾。
參考解法
方法 1:
You can use:
RewriteEngine On
Options ‑MultiViews
# Redirect to http(s)://www
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# remove php
RewriteCond %{THE_REQUEST} ^[A‑Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
# Rewrite to php
RewriteCond %{DOCUMENT_ROOT}/$1.php ‑f
RewriteRule ^(.+)/?$ /$1.php [L]