mod_rewrite VS relative paths

风格不统一 提交于 2019-12-20 14:35:57

问题


My mod_rewrite code is:

Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)?$ index.php?url=$1 [L,NC]

This structure is placed on my server path /beta

When I place the URL http://mydomain.com/beta/download everything works rewriting to the real path http://mydomain.com/beta/index.php?url=download

The problem happens with the relative paths. When I enter the URL http://mydomain.com/beta/download/box the rewriting goes to http://mydomain.com/beta/index.php?url=download/box... but....

All my relative paths, like my css folder, my js folder, image files.... everything with relative path in my index.php page crashes, cuz my relative paths become download/css, download/js, download/images... etc...

I know this problem happens in reason of the slash in the path "download/", but how can I solve that using the mod_rewrite in .htaccess?

Can I prevent rewriting in relative paths? Or even in internal paths of my own domain?

How can I solve that WITHOUT change my relative paths to absolute paths?

Thanks


回答1:


Add a <base href="yoururl.com/beta/"; /> tag to your HTML head. Also add RewriteBase /beta/ to the htaccess if you're in that subfolder




回答2:


you should always use absolute paths for images css etc, when playing with mod_rewrite but simple solution might be to ignore css,js, images and rest in RewriteRule ^(.+)?$ index.php?url=$1 [L,NC]

RewriteRule ((js|css|images)\/.*)$ /$1 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)?$ index.php?url=$1 [L,NC]

however this might not work if these dirs actually depend of the current url




回答3:


I've tested the tag and there's no need to indicate http:// The following code worked for me:

<base href="<?php echo dirname($_SERVER['PHP_SELF']);?>/" />



回答4:


The server won't ever know whtether the request came via relative or absolute path so there is nothing You can do about it. As stated in another answer, You could make exceptions but maintaining all of them etc will become PITA at some point. ;)

I always use absolute paths especially when rewriting so I'd suggest just that, it's the easiest way




回答5:


Adding the line:

<BASE href="http://www.sitename.com/">

to my page inside the <head> tag works great for me. It can be coded even a PHP function to automatize this so you don't have to bother with copy/paste on other occasions.

Update:

<?php
$BaseDir = 'http://'.$_SERVER['SERVER_NAME'].substr($_SERVER["SCRIPT_NAME"], 0, strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
?>

<head>
...
<BASE href="<?php echo $BaseDir; ?>">
...
</head>


来源:https://stackoverflow.com/questions/6333834/mod-rewrite-vs-relative-paths

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!