.htaccess - rewriting url requests and taking care

2019-09-01 01:47发布

问题:

A little question about using htaccess to rewrite uri's and also take care of the fact that browsers requests for included files (like .css files) are "wrong".

First of all, the background: i have this file structure on the server:

/mysite/.htaccess
/mysite/articles.php
/mysite/includes/css-files/layout.css

and into articles.php i have the lines

<style type="text/css">
  @import url(./includes/css-files/layout.css);
</style>

everything should work well, when i directly request the php file. But, since we don't want to request it directly, but using the rewrite rules to make the url user/ceo-friendly, we run into a problem with relative paths. So, for example, having these lines into the .htaccess file

# take care of different requests
RewriteRule ^articles/writer/(\w*)/?$ articles.php?writer=$1
RewriteRule ^articles/tag/(\w*)/?$ articles.php?tag=$1

when the user goes to mysite/articles/writer/erenor, the server redirects the request to mysite/articles.php?writer=erenor. This is good. Then, the browser tries to request the css file, but the request will be the following:

GET mysite/articles/writer/includes/css-files/layout.css

And this is not good. So, i tried to add a rule like this:

# take care of adapting "base url" for css files
RewriteRule /(\w*)\.css includes/css-files/$1.css

It seems to work, and the file is requested from the correct location.

Now, the question(s): is this a correct approach? Could i incur in security issues? Is there something better out in the programmer's world?

Thanks for your support.

回答1:

The approach is probably less desirable as you now have 2 URL's that point to the same resource. Something that you can do is redirect instead of rewrite:

RewriteRule /(\w*)\.css includes/css-files/$1.css [L,R=301]

But the source of your problem is this:

@import url(./includes/css-files/layout.css);

There's a . in front of the /includes which makes it a relative URL, and the browser has to determine what the URI base to use when it goes to request layout.css. As far as it knows, the resource it requested is at /mysite/articles/writer/erenor, so obviously it's going to assume the base is /mysite/articles/writer/. It doesn't know anything about your rewrites and it's doing things the correct way. To avoid this, either change your URLs to be absolute:

@import url(/mysite/includes/css-files/layout.css);

or add the correct relative URI base to the page's header:

<base href="/mysite/" />