Home  >  Article  >  Backend Development  >  How to Remove File Extensions from URLs in NGINX?

How to Remove File Extensions from URLs in NGINX?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 14:02:02189browse

How to Remove File Extensions from URLs in NGINX?

Removing File Extensions from URLs in NGINX

To present a cleaner URL structure, you want to remove ".php" and ".html" extensions from all URLs on your website.

Initially, you successfully removed ".html" extensions using the following configuration:

location / {
    root   html;
    index  index.html index.htm index.php;
    try_files $uri.html $uri/ =404; 
}

However, this configuration doesn't work for ".php" extensions. To resolve this issue, you can modify your NGINX configuration file as follows:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

location @extensionless-php {
    rewrite ^(.*)$ .php last;
}

This configuration will now remove both ".php" and ".html" extensions from all URLs:

  • try_files $uri $uri.html $uri/ checks for the original URL, the URL with a ".html" extension, and the URL as a directory.
  • If none of those files exist, it forwards the request to the @extensionless-php location.
  • try_files $uri =404; in the location ~ .php$ block explicitly returns a 404 error for URLs ending in ".php".
  • Finally, the @extensionless-php location rewrites the URL to add the ".php" extension if it doesn't already exist.

Restart NGINX after making these changes, and your URLs will now be presented without the file extensions.

The above is the detailed content of How to Remove File Extensions from URLs in NGINX?. 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