Home >Backend Development >PHP Tutorial >How Can I Remove File Extensions (like .php) from My Website URLs?

How Can I Remove File Extensions (like .php) from My Website URLs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 16:50:151008browse

How Can I Remove File Extensions (like .php) from My Website URLs?

Removing File Extensions from Website Addresses

In the design of modern websites, it is often desirable to hide file extensions from the URL displayed in the address bar. This helps maintain a clean and user-friendly appearance, as seen on the Stack Overflow website.

Problem Statement

You have created a website and want to remove the file extensions (.php, .jsp) from the displayed URL. For instance, you want users to see "http://something.example/profile" instead of "http://something.example/profile.php."

Solution

To achieve this, you can utilize an .htaccess file placed in the root directory of your website. This file contains instructions for handling URL rewriting. Here's how you can set it up:

  1. Create a new file named ".htaccess" in your website's root directory.
  2. Add the following code to the .htaccess file:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ .php

Explanation

  • RewriteEngine on: Activates the rewrite engine.
  • RewriteCond %{REQUEST_FILENAME} !-d: Checks if the requested file is not a directory.
  • RewriteCond %{REQUEST_FILENAME}.php -f: Checks if the requested file with .php extension exists.
  • RewriteRule ^(.*)$ $1.php: Rewrites the request to add the .php extension only if it is not already present in the request.

This configuration tells the web server to rewrite requests for URLs without .php extensions by adding them, ensuring that the requested PHP file is executed. As a result, the URL displayed in the address bar will appear without the extension.

The above is the detailed content of How Can I Remove File Extensions (like .php) from My Website URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn