Hazz22
Hazz22

Reputation: 1010

.htaccess file works with Errors, but not with rewriting

I've created a .htaccess file, and can get the server to serve me a custom 404 page. However, when i try and do a re-write, it doesn't work.
The htaccess file is located in the root directory.

RewriteEngine On
RewriteRule /htaccessTest/index.php /htaccessTest/phpinfo.php 
ErrorDocument 404 /htaccessTest/errors/404_message.php

I'm not sure as to why this isn't working. I've checked phpinfo, and under Apache2, it states that mod_rewrite has been loaded.
I'm really stumped here.
Not sure what's going on! Any help would be great!

Update 1

As per what was highlighted below, i found that it still didn't work! I've made some changes, and now all I get is the 404 error message, unless I navigate to the index page. Here are the changes:

ErrorDocument 404 /htaccessTest/errors/404_message.php
RewriteEngine On
RewriteRule ^htaccessTest/test\.php$ /htaccessTest/phpinfo\.php$ [L,NC]

And i access it using the url:

localhost/htaccessTest/test.php

(ignore the lack of http://, I've removed so that it didn't think it was a link).
Any further ideas?

Thanks

Upvotes: 0

Views: 76

Answers (2)

Hazz22
Hazz22

Reputation: 1010

Finally found the answer after hacking around with it.

It seems to be the first part of the Rewrite. There is a difference with the first and second section that I didn't realise, which is that the URL sort of "resets" when using Rewrite.

This is explained easier by giving you the now re-worked example.

Original:

RewriteRule ^htaccessTest/test\.php$ /htaccessTest/phpinfo\.php$ [L,NC]

New:

RewriteRule ^test.php /htaccessTest/phpinfo.php

As you can see, the first part references htaccessTest. You don't need this part, as the url was "already in" this file structure. Your url being: "localhost/htaccessTest/test.php"

The second part stays roughly the same, I just removed the Regex stuff and the [L,NC]. The [L, NC] will probably come in handy later, but for simplicity sake I removed it.

The result is this:

ErrorDocument 404 /htaccessTest/errors/404_message.php
RewriteEngine On 
RewriteRule ^test.php /htaccessTest/phpinfo.php

Thanks for the help guys! (Especially @anubhava)

Upvotes: 0

anubhava
anubhava

Reputation: 785406

Try your rule without leading slash:

ErrorDocument 404 /htaccessTest/errors/404_message.php

RewriteEngine On
RewriteRule ^htaccessTest/index\.php$ /htaccessTest/phpinfo.php [L,NC]
  • Better to use line start/end anchors to avoid matching unexpected text in an URI.
  • dot needs to be escaped in a regex which otherwise matches any character.
  • .htaccess is per directory directive and Apache strips the current directory path (thus leading slash) from RewriteRule URI pattern.

Upvotes: 3

Related Questions