URLs or Uniform Resource Locators are the addresses of web pages on the internet. They are used to locate and access websites, pages, and files. Sometimes, URLs may contain a file extension such as “.html” at the end, which indicates that the page is an HTML document. While it doesn’t affect the functionality of the website, some people prefer to remove the “.html” extension from the URLs for various reasons, such as aesthetics, search engine optimization (SEO), or usability. In this article, we will discuss the proper method on how to remove .html from URL using PHP and JavaScript.

Using .htaccess and mod_rewrite in PHP

The most common and effective way to remove .html from the URL is to use .htaccess and mod_rewrite. Here’s how to use them:

Step 1:

Enable mod_rewrite module: Before using mod_rewrite, you need to make sure that the mod_rewrite module is enabled on your web server. You can do this by checking the Apache modules on your server.

Step 2:

Write a Rewrite Rule: Once the mod_rewrite module is enabled, you can write a rewrite rule to remove .html from the URL. Here’s an example:

how to remove .html from url
how to remove .html from url

The above rule will redirect all URLs that end with “.html” to the same URL without the “.html” extension.

Step 3: Test the Rewrite Rule: Once you have written the rewrite rule, you need to test it to ensure that it is working.

Using JavaScript:

If you don’t have access to the server configuration, you can use JavaScript to remove .html from the URL on the client-side. Here’s how to do it:

Step 1:

Get the current URL: You can get the current URL using the window.location.href property in JavaScript.

how to remove .html from url
how to remove .html from url

Step 2:

Remove .html from the URL: Once you have the URL, you can remove the “.html” extension using the replace() method in JavaScript.

how to remove .html from url
how to remove .html from url

The above code will remove the “.html” extension from the URL.

Step 3:

Redirect to the new URL: Once you have removed the “.html” extension from the URL, you can redirect the user to the new URL using the window.location.href property.

how to remove .html from url
how to remove .html from url

The above code will redirect the user to the new URL without the “.html” extension.

Conclusion:

In this article, we have discussed two methods to remove .html from the URL using PHP and JavaScript. The first method uses .htaccess and mod_rewrite to remove .html from the URL on the server-side. The second method uses JavaScript to remove .html from the URL on the client-side. Both methods are effective and can be used depending on the server configuration and the specific requirements of the website.


By umarbwn