Stylesheets break when rewriting a URL like profil

2019-08-06 08:39发布

问题:

I have this code in an .htaccess file:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^profile/(.*)$ profile.php?username=$1

My CSS stylesheet is working on all pages, except those matching the last rule (for the profile):

RewriteRule ^profile/(.*)$ profile.php?username=$1

For example, when I type www.mydomain.com/register, the stylesheet is working. But when I type www.mydomain.com/profile/username, the stylesheet doesn't work.

My stylesheets and other auxiliary files are in separate folders: css/, images/, js/, etc.

What can i do? Please help :D


Edit: I have a header and a footer like this: includes/header.php, includes/footer.php. In the file header.php is the PHP code:

<?php include 'head.php'; ?>

In this head.php is the meta tag for CSS:

<link rel="stylesheet" href="css/screen-site.css">

Here's a screenshot of the folder structure: http://shrani.si/f/3z/13T/1OKC8ZJc/site.png

回答1:

You can also create a variable in a config.php file with your base url:

$base_url = "http://www.yourdomain.com/";

Then in your header file:

<link href="<?php echo $base_url; ?>css/style.css" />


回答2:

The problem is that those are all internal rewrites. So, even though your webserver is sending data from /profile.php?username=whatever, the browser still thinks it's receiving a page from http://www.mydomain.com/profile/whatever.

Thus, when it sees a relative URL like css/screen-site.css, it resolves it to http://www.mydomain.com/profile/css/screen-site.css, which does not exist.

I can think of at least three different ways to solve the problem:

  1. The simplest and probably best solution would be to prepend a / to your links, so that they look like /css/screen-site.css. The slash makes the browser treat the URL paths as relative to the root directory of your site, rather than (what it believes to be) the current directory.

  2. Alternatively, you could include a base tag in your HTML head section, as slash197 suggests, something like <base href="http://www.mydomain.com/">. That way, all relative URLs in your HTML will be interpreted as relative to the root of your site.

  3. You could also fix the issue with more rewrite rules, something like:

    RewriteRule ^profile/((css|images|js)/.*) $1 [L]
    

    This is less efficient than the first two solutions, however, since the browser won't realize that the different URLs actually refer to the same style sheet (and even if you use an external rewrite to tell it that they do, it still needs to query the server to find out).