If you’re running a website on an Apache server, the .htaccess file is one of the most powerful tools at your disposal. It allows you to control how your URLs behave — from redirections to clean URL rewriting — without needing to change your actual server configuration.

In this article, we’ll cover the basics of URL redirection and rewriting using .htaccess, with clear examples and explanations.

What Is the .htaccess File?

.htaccess stands for Hypertext Access. It’s a configuration file used on Apache-based web servers that allows you to make directory-level changes to server behavior.

You can:

  • Redirect traffic from one URL to another

  • Create clean URLs (e.g., /about instead of /about.php)

  • Restrict access to certain pages

  • Enable HTTPS

  • And much more

Redirecting URLs

1. 301 Permanent Redirect

Use this when a page has permanently moved to a new URL.

Redirect 301 /old-page.html https://yourdomain.com/new-page.html

2. 302 Temporary Redirect

Use this when the redirection is temporary.

Redirect 302 /temp-page.html https://yourdomain.com/coming-soon.html

3. Redirect with mod_rewrite

You can also redirect using RewriteRule:

RewriteEngine On
RewriteRule ^old-page$ https://yourdomain.com/new-page [R=301,L]

Rewriting URLs (Clean URLs)

URL rewriting is used to make URLs more user- and SEO-friendly. For example, instead of:

https://example.com/product.php?id=123

You can use:

https://example.com/product/123

1. Basic Rewriting Rule

RewriteEngine On
RewriteRule ^product/([0-9]+)$ product.php?id=$1 [L]

This tells Apache:

  • When someone accesses /product/123

  • Internally rewrite it to product.php?id=123

2. Remove .php Extension

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.]+)$ $1.php [L]

This allows users to access example.com/about instead of example.com/about.php.

Best Practices

  • Always backup your .htaccess file before making changes.

  • Use [L] to stop further rules from being processed once a match is found.

  • Test your redirects with tools like httpstatus.io.

  • Don’t mix Redirect and RewriteRule too much in the same block — prefer RewriteRule for consistency.

Bonus: Force HTTPS with .htaccess

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

This forces all traffic to use HTTPS — essential for modern security and SEO.

Conclusion

The .htaccess file gives you incredible control over how your URLs work. Whether you’re redirecting old pages, cleaning up messy URLs, or securing your traffic, mastering these simple rules can greatly improve your website’s performance and user experience.