HTAccess: Rewrite
RewriteEngine on
RewriteRule pattern substitution [flags]
RewriteEngine on
RewriteRule ^about.html$ aboutus.html
In the above example, ^about.html$ is the pattern and aboutus.html is the substitution. If a user tries to access the about.html page, they are redirected to aboutus.html.
Let’s move on to more complex scenarios. Suppose we have a dynamic website where user profiles are accessed via a URL like www.example.com/profile.php?user=username. We can rewrite this URL to a more user-friendly format, such as www.example.com/username.
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
Here, ^([a-zA-Z0-9_-]+)$ is a regular expression that matches any alphanumeric string (including underscores and hyphens). When a match is found, it’s passed as a parameter to profile.php.
Another common use case is implementing a trailing slash redirect, which ensures each of your URLs points to a directory rather than a file. This is beneficial for SEO purposes.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*[^/])$ $1/ [L,R=301]
In this example, the RewriteCond directive sets conditions for the RewriteRule to be triggered. The two conditions check that the request isn’t for a file and that the URL does not end with a slash. If both conditions are met, the RewriteRule adds a trailing slash to the URL and issues a 301 (permanent) redirect.
Source:
https://www.digitalocean.com/community/questions/htaccess-rewrites-an-in-depth-guide-with-practical-examples