Home > other >  URL Rewriting in .htaccess (Apache) displaying 404-Error
URL Rewriting in .htaccess (Apache) displaying 404-Error

Time:07-31

this is my first question here on stackoverflow because in the past I always found a question that described my problem perfectly. But now they were not able to do that, so I decided to ask for help myself.

My goal is to display profiles, but the url shouldn't look like "/profile/show-profile.php?user=admin", just "/profile/admin".

So looked it up on google and found URL rewriting to be potentially useful, by editing the .htaccess file.

The problem is, it doesn't work. I already have some things in my .htaccess (redirecting to https and the 404-Page "/pagenotfound.php") and it seems like they don't work in combination.

# https redirecting

RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^(.*)$ https://int-politics.com/$1 [R=301]`

# 404 page

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /pagenotfound.php
ErrorDocument 404 /pagenotfound.php

# URL REWRITING

RewriteEngine On
RewriteBase /profile/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ show-profile.php?user=$1

When I add the URL Rewriting part the 404-Page doesn't work anymore. Every site that doesn't exist just outputs "/pagenotfound.php" (see image -->) Not-existing site just outputs /pagenotfound.php instead of showing it. And the url-rewriting doesn't work too.

It would be wonderful if you could help me with this problem and tell me whats wrong. Thank you very much!

CodePudding user response:

You usage of the RedirectBase is wrong. It should appear only once in such a distributed configuration file. Actually it is not required in this example at all ... Please take a look into the documentation for details on that: https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase

Also it is vital to understand that the rewriting engine loops if a rule gets applied. And why that makes using the L or the END flag so important.

That probably is what you are looking for:

RewriteEngine On
RewriteBase /

# https redirecting
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://int-politics.com%{REQUEST_URI} [R=301,END]

# profile rewriting
RewriteRule ^/?profile/(\w )$ /profile/show-profile.php?user=$1 [END]

# 404 page
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /pagenotfound.php [END]
ErrorDocument 404 /pagenotfound.php

Best is to implement such rules in the central http server's host configuration. If you do not have access to that (read: if you are using a cheap hosting provider) then you can use a distributed configuration file instead, if the consideration of such files has been enabled (see the documentation for the AllowOverride directive on that).

  • Related