Home > Blockchain >  redirecting about.php to domain.com/About/ using .htaccess rewrite rules
redirecting about.php to domain.com/About/ using .htaccess rewrite rules

Time:02-02

When I write RewriteRule About About.php [L,QSA] in .htaccess to make users access example.com/About.php using the following link example.com/About/. Users can access it correctly if it was written as example.com/About only. If I added more backslack like this example.com/About/ the CSS files are not loaded. Also, if anyone accessed this link example.com/About/SomeText he didn't get error 404 he gets about.php page without loading CSS as well.

CodePudding user response:

RewriteRule About About.php [L,QSA]

The problem with this rule is that it rewrites any URL that simply contains the word "About". So, /About/SomeText, /AnythingAbout and /AbcAboutXyz are all rewritten to About.php which processes the request. (It also rewrites itself, which is another matter!)

You need to be specific and match only requests for /About exactly. For example:

RewriteRule ^About$ About.php [L]

The first argument to the RewriteRule directive is a regex that matches against the requested URL-path (less the slash prefix).

The QSA flag is not required here.

If I added more backslack like this domain.com/About/ the CSS files are not loaded.

"backslack" - that is a (forward) "slash" (and not a "backslash" either).

This will happen if you are using relative URL-paths to access your CSS files (and other static resources like images and JS). The relative URL-path is resolved by the browser relative to the current URL. eg. If you are linking to your stylesheet with href="styles.css" and the current URL in the browser is /About/SomeText then the browser will naturally request /About/styles.css, not /styles.css as you might be expecting (when the URL is simply /About).

When rewriting the URL at different path depths you need to use either:

  • Root-relative (starting with a slash) URL-paths.
  • Absolute URLs (with scheme hostname).
  • Specify a base element in the head section of the HTML source that tells the browser what URL should be used as the base for all relative URLs. Although there are caveats with this approach (as mentioned in the linked question below)

(Although, in restricting the above rule to match /About only then this naturally avoids this issue.)

See also my answer to the following question that goes into more detail on this:

  • Related