Home >Backend Development >PHP Tutorial >How can NGINX be configured to eliminate file extensions from URLs?

How can NGINX be configured to eliminate file extensions from URLs?

Barbara Streisand
Barbara StreisandOriginal
2024-11-22 07:00:11961browse

How can NGINX be configured to eliminate file extensions from URLs?

Eliminating File Extensions: A Comprehensive Guide Using NGINX

In web development, the appearance of file extensions in URLs can often be aesthetically unappealing. NGINX, a popular web server, offers flexible configuration options to remove these extensions and enhance the overall user experience.

Extending URL Beauty: Dealing with .html Files

To remove the ".html" extension from "indexhtml.html," the following configuration snippet can be included in the "/etc/nginx/conf.d/domain.tld.conf" file:

try_files $uri $uri.html $uri/

Conquering .php URLs: A Tale of Two Locations

To tackle the removal of ".php" extensions, a slightly more sophisticated approach is required. The following block of configuration should be added to the same file:

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

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

Bridging the Gap: Integrating the Two

The two aforementioned configurations can be seamlessly integrated using the following code:

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

Finalizing the Process: Restart and Reap the Benefits

Once these configurations are in place, restart nginx and witness the transformation:

  • "indexhtml.html" will優雅轉變為 "indexhtml".
  • "indexphp.php" will unveil itself as the sleek "indexphp".

This technique empowers developers to createURLs that are both aesthetically pleasing and search engine friendly.

The above is the detailed content of How can NGINX be configured to eliminate file extensions from 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