Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess, Redirect Non-Existing Except a Few URL Rewrites

I have a webpage where if non-existing files or folders were to be typed by a user http://wwww.somewebsite.com/nonexistingfolder or http://www.somewebsite.com/nonexistingfile.html will just simply forward to www.somewebsite.com. Then would like to create a web page from www.somewebsite.com/about.html to www.somewebsite.com/about since shorter is better in my opinion. Using .htaccess I thought I could use RewriteCond for non-existings and RewriteRule for the user-friendly like web page url. I'm terrible at .htaccess I only know basics, I did my research even the questions that may have been asked already but not sure how to write this exception rule.

How can I add a code in .htaccess so that I can have all non-existing files/folders except the web page url I specified?. This one below will simply redirect all non-existings to index.html and when I do www.somewebsite.com/about (from /about.html) simply goes to index.html. Any help?

--- my .htaccess shows --
# Redirect non-existing files or folders to index
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ / [L,QSA]
</IfModule>

# Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
RewriteEngine on
RewriteRule ^/$    index.html [L]
RewriteRule ^about/$    about.html [L]
RewriteRule ^services/$    services.html [L]
RewriteRule ^application/$    application.html [L]
RewriteRule ^contact/$    contact.html [L]
RewriteRule ^privacy/$    privacy.html [L]
like image 511
mythoslife Avatar asked Nov 02 '22 11:11

mythoslife


1 Answers

You need to do the all-or-nothing rewrite (e.g. the RewriteRule ^(.*)$ / [L,QSA]) after all of your other more specific rules. The rules all get applied in the order that they appear in, so this means your first rule simply always gets applied, and then the rewrite engine stops.

Swap the order around and try again:

# Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
RewriteEngine on
RewriteRule ^/?$    index.html [L]
RewriteRule ^about/$    about.html [L]
RewriteRule ^services/$    services.html [L]
RewriteRule ^application/$    application.html [L]
RewriteRule ^contact/$    contact.html [L]
RewriteRule ^privacy/$    privacy.html [L]

--- my .htaccess shows --
# Redirect non-existing files or folders to index
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ / [L,QSA]
</IfModule>

Also this rule:

RewriteRule ^/$    index.html [L]

Will never get applied because leading slashes are removed from the URI before applying rules to them, so ^/$ will never match, you want ^$ or ^/?$ instead.

like image 182
Jon Lin Avatar answered Nov 09 '22 12:11

Jon Lin