URL重写:css,js和图像未加载

Bha*_*ani 20 php apache .htaccess mod-rewrite url-rewriting

我遵循规则 .htaccess

Options +FollowSymLinks

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f [OR]

RewriteRule ^detail/([0-9]+)/?$ detail.php?id=$1
Run Code Online (Sandbox Code Playgroud)

它将http://localhost/detail/123URL 重定向到http://localhost/detail.php?id=123.页面重定向成功,但问题是CSS, JS, and images没有加载,

CSS,js文件位于http://localhost/css/http://localhost/js/

一种解决方案是使用绝对路径(ex/CSS或/ js而不仅仅是CSS /,/ js,但这似乎不是一个可靠的解决方案,因为我们要在所有文件上更改它,

.htaccess基于规则的任何其他解决方案,它独立于编辑所有PHP文件并让我们使用"相对路径"?

Jon*_*Lin 21

一个解决方案是使用绝对路径(ex/css,或/ js而不仅仅是css /,/ js,但这看起来不是一个可靠的解决方案,因为我们要在所有文件上更改它,

这是因为您的相对URI的基数已更改.最初,基础是/页面的时间/detail.php?id=123,并且浏览器正确地填充与/基础的相对链接.但是当浏览器/detail/123突然变为基础的页面时/detail/,它会尝试将其附加到所有相对URL之前,因此它们都不会加载.

您可以将链接设为绝对链接,也可以更改页面标题中的URI基数(在<head> </head>标记之间):

<base href="/">
Run Code Online (Sandbox Code Playgroud)


Ant*_*los 19

不要懒惰并更改资源中的相对URI.这是最好的.

你可以聪明地使用正则表达式并替换你需要的所有文件,就像几个衬里一样,你就完成了.有多少地方可以改变?你应该使用模板.

这应该工作,但我不会这样做.

/css/style.css

  • @BhaveshGangani有点赞,但**不是**与协议和域`http:// example.com/css/style.css`,但这种类型的根目录绝对路径:`/ css/style. css` (2认同)

Saj*_*jal 6

我将url重写应用于核心php中的项目.我遇到了同样的问题.css,Js和图像没有加载.我用过这个,它对我有用.资源

# Allow any files or directories that exist to be displayed directly
RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|php|ico|txt|pdf|xml)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
Run Code Online (Sandbox Code Playgroud)