.htaccess: Pretty URLs and subfolders

47 Views Asked by At

I do not use subfolders except for images but somehow Google find links to subfolders which results in an indexing error. Example: https://example.com/mobile/page - the mobile folder does not exist.

I have this in my .htaccess:

RewriteRule ^([^/.]+)$ /index.php?page=$1 [L,B]
RewriteCond $1 !(\.(png|ico|css)|index\.php)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php? [L]

When requesting the above URL, the index.php is shown but without fetching the css file and images. I guess that it works from the folder "mobile" instead of the root folder.

How do I serve a 404 error to Google and redirect to the index.php in the root folder for real people following such a link?

I am not a programmer, I am only good at copying code :-/ I haven't been able to find the code necessary to solve the problem.

1

There are 1 best solutions below

1
Kim Ludvigsen On

I ended up with a mix of .htaccess and PHP. In case this can help others that get a lot of errors in Googles search console due to non-existing URLs somewhere on the internet:

In .htaccess I have this:

RewriteCond $1 !(.(png|ico|css)|index.php)$

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)$ https://example.com/nopage? [L]

That redirects the non-existing URLs to "nopage". In PHP I catch the "nopage" and serve an error page for the human visitor with a 404 header for Googles search bot:

header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");

I can understand from arkascha's answers that my .htaccess code does not check whether a file exists, however, it works like a charm.