How to remove the .html extension from the URL of a static page?
How can I create a custom URL for a static page without .php or .html extensions?
I would like my URL to appear as http://www.example.com/about, without any .html suffix ( http://www.example.com/about.html) attached.
Is it possible? The website is built using only HTML/CSS.
✅ You can achieve this using a rewrite engine(server level configuration) or by utilizing an HTML folder structure. This method is also the same for .php files; you can replace .php with .html.
Method 1:
To remove the " .html" extension from the URLs of static pages on a website, you'll generally need to configure your web server to handle such requests appropriately. The exact steps can vary depending on the web server you're using. Below are instructions for two popular web servers: Apache and Nginx.
Apache Server:
If you're using the Apache web server, you can achieve this using the mod_rewrite module. Here's how:
Enable mod_rewrite: Make sure mod_rewrite is enabled on your server. You can usually do this by running sudo a2enmod rewrite on Linux.
Create or edit the .htaccess file: In the root directory of your website, create a file named .htaccess if it doesn't already exist. Add the following code to it:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.html -f RewriteRule ^([^\.]+)$ $1.html [NC,L]
This code checks if a directory with the requested name doesn't exist and if a file with the ".html" extension exists. If both conditions are met, it rewrites the URL to include the ".html" extension.
Nginx Server:
For Nginx, you can achieve URL rewriting using the location block and the try_files directive. Here's how:
Edit your Nginx configuration file: Locate your site's configuration file (often found in /etc/nginx/sites-available/) and open it for editing.
Add a location block: Within the server block, add a location block like this
location / { try_files $uri $uri.html $uri/ =404; }This code tells Nginx to try finding the requested file without an extension, and if that fails, to try finding the file with the ".html" extension.
Reload Nginx: After making changes, reload or restart Nginx for the changes to take effect.
Remember to back up your server configuration before making any changes, and test thoroughly to ensure everything works as expected.
Keep in mind that making server configuration changes can have unintended consequences if not done correctly. If you're not comfortable with these configurations, consider consulting with a server administrator or web developer for assistance.
Method 2:
Generate a subdirectory named "about" within your web files directory, and proceed to place the HTML file " index.html" inside it.
The server will automatically retrieve the "index.html" file as the default content when the browser accesses that specific (/about) directory level. This solution is straightforward and uncomplicated.