我在我的 PC 上使用 WAMP 服務器作為本地主機。我想在沒有 PHP 擴展的情況下重寫我的 URL,并從http://myproject/post.php?page=page_slugto中洗掉查詢字串(但可讀) http://myproject/post/page_slug,我應該能夠通過echo $_GET['page'];“post.php”頁面讀取“page_slug”。為此,我在下面共享了一個具有簡單層次結構的專案。
專案檔案夾:
- ->css/style.css
- ->影像/標志.jpg
- ->js/script.js
- ->.htaccess
- ->索引.php
- ->關于.php
- ->聯系人.php
- ->博客.php
- ->post.php
- ->page.php
現在我想從我的 URL 中洗掉所有 .PHP 擴展名,所以我使用了下面的 .htaccess 代碼,它作業正常。
# Options is required by Many Hosting
Options MultiViews
#Remove .PHP Extension And Force Redirect To Without .PHP File Name In URL
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]
#RewriteCond %{THE_REQUEST} \s([^?]*)\?p=(\S )\s [NC]
#RewriteRule ^ %1/%2? [R=301,L]
在上面的代碼之后,我可以將我的 URL重寫http://myproject/post.php?page=page_slug為http://myproject/post?page=page_slug.PHP 擴展名現在已成功洗掉。
Now to make my URL free from query string pattern, I used the below code after the above code in my .htaccess file.
RewriteCond %{THE_REQUEST} \s([^?]*)\?p=(\S )\s [NC]
RewriteRule ^ %1/%2? [R=301,L]
After the above code, I am able to re-write my URLs from http://myproject/post?page=page_slug to http://myproject/post/page_slug means query string is now removed successfully but my JS and CSS are broken now as shown below.

But my every file is perfect as when I remove the upper second code set then it is working properly. Also, they are loading fine as shown below.

I noticed one thing that my CSS and JS files data is now changed with my PHP file data as shown below. Why this is happening...???

So what is the fix for this...??? Also, remember that I need to read QUERY STRING parameters also in my file.
uj5u.com熱心網友回復:
“問題”是您似乎正在使用靜態資源(CSS、JS 和影像)的相對 URL 路徑。所以這是一個客戶端 URL 決議問題。您應該對資產使用根相對(以斜杠開頭)或絕對(使用方案 主機名)URL,以便無論 URL 路徑深度如何,都可以定位它們。(請注意,您的 JS 發出的任何請求,例如 AJAX,也應該是根相對或絕對的。)
問題不在于.htaccess,但是當您將 URL 從 更改為 時/post.php?page=page_slug,/post/page_slug任何客戶端相對 URL 都將決議為相對于/post/,而不是/像以前那樣(檔案根目錄)。
對 JS(和 CSS)檔案的請求導致 404,因此 404 HTML 錯誤檔案很可能被決議為 JS 并且失敗(即“未捕獲的語法錯誤:意外令牌:'<'” - 由于 a<!DOCTYPE html>或打開<html>標簽)。
一種可能的解決方法(避免更改 URL)是使用base該部分中的 HTML 元素head來指示任何相對 URL 應相對于什么進行決議,覆寫當前檔案的 URL。但是,如果您使用表單的頁內錨點,這還有一些額外的注意事項href="#element"- 因為它們現在將相對于base元素中宣告的檔案而不是當前檔案進行決議。
另請參閱我對網站管理員堆疊上以下問題的回答,該問題對此進行了更詳細的說明:
- https://webmasters.stackexchange.com/questions/86450/htaccess-rewrite-url-leads-to-missing-css
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/449232.html
標籤:javascript php css .htaccess url-rewriting
上一篇:.htaccess:如果設定了get引數,則if陳述句禁用密碼保護
下一篇:我無法更改我的流媒體網站主頁
