How to make clean urls with .htaccess?

by jaycee_rowe , in category: SEO , 6 months ago

How to make clean urls with .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by virginie , 6 months ago

@jaycee_rowe 

To make clean URLs with .htaccess, you can use the mod_rewrite module in Apache. Here's an example of how you can achieve this:

  1. Create a .htaccess file if you don't already have one in the root directory of your website.
  2. Open the .htaccess file and add the following code: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
  3. Save the .htaccess file.


Explanation of the code:

  • RewriteEngine On enables the URL rewriting engine.
  • RewriteCond %{REQUEST_FILENAME} !-f checks if the requested URL is not an existing file.
  • RewriteCond %{REQUEST_FILENAME} !-d checks if the requested URL is not an existing directory.
  • RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] redirects all requests to the index.php file while passing the requested URL as a query parameter (url). The [QSA,L] flags mean "query string append" and "last rule," respectively.
  1. Test the clean URLs by accessing your website with URLs like http://example.com/page instead of http://example.com/index.php?page.


Note: For this to work, you should also update your PHP code (in this example, the index.php file) to handle the url query parameter and map it to the appropriate content on your website.