Home > Software engineering >  Write an htaccess file with specific rules
Write an htaccess file with specific rules

Time:02-13

So basically I'm trying to write the below rules:

Assuming I have this website: www.example.com

  1. HTTP -> redirect to -> HTTPS

  2. www -> redirect to -> non-www

  3. https://example.com/xyz -> rewrite to -> https//example.com/post.php?id=xyz

All these rules should be working at the same time. I tried the below sample:

RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]

Thank you so much for your help.

CodePudding user response:

RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]

Your first line looks like a typo(?) as it doesn't make sense.

Your second rule (a rewrite) is pretty much correct in order to rewrite the request to post.php?id=<url>. However, strictly speaking, the two conditions are in the wrong order considering the second condition is really only required for efficiency. Filesystem checks are relatively expensive, so you should be excluding requests for your static resources (using a regex string comparison) before resorting to a filesystem check.

So, before this rewrite you just need to add a HTTP to HTTPS and www to non-www redirect, which could be implemented as one or two rules.

Try the following instead:

RewriteEngine On

# HTTP to HTTPS and www to non-www generic redirect
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(. ?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

# Rewrite requests to "post.php"
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) post.php?id=$1 [L]

NB: Test first with a 302 (temporary) redirect to avoid potential caching issues.

%1 in the first rule is a backreference to the last matched CondPattern. ie. This holds the domain name, less the www. subdomain (if any).

With regards to the HTTP to HTTPS redirect, this does assume the SSL cert is installed directly on your application server and you aren't using a front-end proxy that is managing your SSL cert.

If you are not expecting URLs to contain .php extensions then you should also consider adding this to the list of stated extensions in the RewriteCond directive.

  • Related