Apache Rewrite URL Creating Linking Issues

元气小坏坏 提交于 2019-12-24 01:43:33

问题


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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/16378984/apache-rewrite-url-creating-linking-issues

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