Sparky
Sparky

Reputation: 98718

Mod-Rewrite rules are breaking 404 routing

I am using the following mod-rewrite in my .htaccess file:

RewriteRule ^$ pages/
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ pages/$1 [L]

The intention is to hide the subdirectory called /pages/ from displaying in the URL.

So this: http://mysite.com/pages/home.html

Will look like this: http://mysite.com/home.html

It works but there are some unintended consequences.

As a direct result of the .htaccess code I posted above, my 404 routing is no longer working at all. Anything that should trigger a 404 error page is instead generating a 500 Server Error.

How to fix?


EDIT:

As implied above, it does not matter if a custom 404 page is defined in the .htaccess or not. Without it, or a bad path to the error page, the server should still route to its default 404 page, and not give a 500 Server Error.

Surely, there must be a standard way to suppress sections of a URL without breaking the normal routing of 404 errors. From my online research it seems that my method above commonly breaks the 404 routing, and yet so far, I've seen no applicable solution. (This is not a Wordpress installation; just static HTML content)


EDIT 2:

Since I'm only wanting to suppress the one directory from the URL, I never mentioned that I also have other files & directories which are siblings to /pages/ that cannot be pointed at /pages/, such as /graphics/, /includes/, /css/, /cgi-bin/, robots.txt, favicon.ico, etc.

Maybe this is all an exercise in futility or more trouble than it's worth?

Looking for a definitive answer either way.

Upvotes: 0

Views: 529

Answers (4)

Sparky
Sparky

Reputation: 98718

Thank-you to @Kamil Šrot for getting the closest working solution. However, I needed to add another test ( -d ) to see if the requesting URI is a directory.

This is working great and the 404 error page is again routing properly.

RewriteEngine On
RewriteBase /
RewriteCond %{DOCUMENT_ROOT}/pages/%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/pages/%{REQUEST_URI} -d
RewriteRule ^(.*)$ /pages/$1

Upvotes: 0

Kamil Šrot
Kamil Šrot

Reputation: 2221

Following config will look for your static pages inside the pages/ and if found, it'll display them. This shouldn't break 404. Put it in root folder of your web in .htaccess

RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}/pages/%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/pages/%{REQUEST_URI} -d
RewriteRule ^(.*)$ /pages/$1

Upvotes: 3

Sameh
Sameh

Reputation: 346

This should achieve what you are trying to do.

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/([a-zA-Z0-9\_\-]+)\.html$
RewriteRule (.*) /pages/$1 [L]

Upvotes: 0

Hoang Huynh
Hoang Huynh

Reputation: 1403

How about adding an error page direction to your htaccess file to handle the 404 page:

ErrorDocument 404 /path/to/your/404.html

Upvotes: -1

Related Questions