TimNguyenBSM
TimNguyenBSM

Reputation: 827

Apache Rewrite URL Creating Linking Issues

Problem: rewrite url causing some links to break.

.htaccess has below rule:

RewriteRule ^blog/([0-9]+)/[-0-9a-zA-Z]+$ index.php?action=blog&postID=$1\%23disqus_thread [NC]

Style sheet reference in header template:

<link rel="stylesheet" type="text/css" href="style.css" />

I can click on:

domain.com/blog/1/title-of-article and get to the file just fine, but style sheet link breaks

If I go directly to:

domain.com/index.php?action=blog&postID=1#.UYV1mcqRiSo then the style sheet loads fine (ignore #.UYV1mcqRiSo, that is code from Disqus).

This is also breaking my logo link, which is:

<a href="./">

Instead of taking me to domain.com, it's going to domain.com/blog/1/

My basic file structure is:

index.php and style.css is in root, which loads up viewPost.php in/templates folder.

What is going and how do I correct this?

Upvotes: 2

Views: 179

Answers (2)

pilsetnieks
pilsetnieks

Reputation: 10430

1. About the stylesheet link

You have to include these conditions in your .htaccess before the rewrite rule:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

The first means that rewrite rules work only if the requested URL is not to an existing file, and the second does the same for existing directories. Without these conditions the request for style.css is also passed to your index.php file, not to the style.css file directly.

If you have these rules already and it still doesn't work then the problem is with URL paths, see below.

2. About URL paths

You're using relative URLs in your links, both in the <a href="./"> and in the <link> tag. In this case they are resolved to the current directory of the URL (it doesn't matter that it's rewritten to the same file serverside, the path is prepared on the client side and every part separated with a slash / is treated as a directory. Thus if the current URL is domain.com/blog/1/, ./ is resolved to domain.com/blog/1/.) The path to style.css may be resolved to domain.com/blog/1/style.css. If you want these links work as if they're directly after the domain name in the URL, you have to use absolute URLs, i.e., / without the dot for the link on your logo; /style.css for the stylesheet link.

Upvotes: 4

C3roe
C3roe

Reputation: 96424

Easiest solution: Just set your links relative to the domain root, by fronting them with a slash (resp. removing the dot referring to the current folder in the link):

<link rel="stylesheet" type="text/css" href="/style.css" />
<a href="/">Logo</a>

Upvotes: 2

Related Questions