2

Currently I'm working on a PHP blog. Where I have used an .htaccess file to get a clean URL, here is the code:

RewriteEngine On
RewriteCond %{HTTPS} !=off
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^([0-9]+)/([a-zA-Z0-9_-]+)?$ post.php?post_id=$1&title=$2 [L]
RewriteRule ^(.+)/(admin|css|fonts|ico|include|js|images)/(.*)$ $2/$3 [L]

I got this code online. As I'm new to PHP and this .htaccess thing, that's why I don't have much idea about it.

URL Before adding .htaccess file was:

http://www.example.com/post.php?post_id=12&title=post-title

And, URL after adding .htaccess file:

http://www.example.com/12/post-title

So RewriteRule gave me the URL that I want. But it has caused an error in redirection of the page. Before using .htaccess file whenever I clicked on home button after visiting following URL:

http://www.example.com/post.php?post_id=12&title=post-title

then URL redirected successfully to home page, that is:

http://www.example.com/index.php

But now after using .htaccess file after visiting the same URL it is redirecting like this:

http://www.example.com/12/index.php

And now it is firing 404 page not found error. Because technically there is no such page present under 12 directory on server. So basically it appends 12 in front of every file.

So after visiting the following link: http://www.example.com/12/post-title I want it to redirect properly as it was redirecting the pages before adding the .htaccess file.

1 Answer 1

1

It sounds like you are (incorrectly) linking to a relative URL (eg. index.php) instead of a root relative URL (starting with a slash, eg. /index.php) or even an absolute URL (Scheme + host + URL-path).

For example, if you link to index.php and you are at the URL /12/post-title then this will naturally resolve to /12/index.php (incorrect). Whereas if you were to link to /index.php then this will resolve to /index.php (correct).

However, do you really want index.php in your URLs? You would normally want to link to the directory (with a trailing slash) and let the server respond with the appropriate directory index. For example:

<a href="/">Home</a>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.