當前訪客身份:游客 [ 登錄 | 加入程式開發 討論區 ]
當前訪客身份:未登入或非會員
alumi alumi
131231

Accessing .php Pages Without the Need for the .php

發表於(2014-07-12 09:48:44)  閱讀(424) | 評論(2 0人收藏此文章,
摘要 Accessing .php Pages Without the Need for the .php Extension

This posts covers setting up your web server to allow access to .php pages without the need for the .php extension. You can also easily modify these examples to work with other extensions as well. This trick is useful for making your URL more friendly and easier to remember. In this post I will show you example code to accomplish this on three different web servers. First I will cover doing so on the Apache web server using a .htaccess file after which an example for Internet Information Services (IIS) using a Web.config file then I will give the code to configure Nginx to do so as well. So let us begin with Apache.

Apache

In order to allow access to .php files without the .php extension in the URL you will first need to ensure mod_rewrite is available. In most cases this module is available. Next we will need to create a file named “.htaccess” if the file does not already exist in the root directory of your site. Now open this file and add the following two lines to it:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L, QSA]

After adding these lines save the file and place it in the root directory of your web server.

Internet Information Server (IIS)

Accomplishing this for a site being served by IIS is not much harder than it is for Apache. This time you will need to create a file named “Web.config”. The following code is an example of a complete Web.conf file which will allow access to .php files without the need to use the .php extension. Again this file may already exist within the root directory of your site. If it does modify the existing file by adding the following configuration settings within the proper place within the existing Web.config.



    
        
            
                
                    
                    
                    
                        
                        
                        
                    
                    
                
            
        
    

Nginx

Configuring Nginx to remove the need to use the .php extension is a little more tricky than the others. You will need to be able to edit the server’s configuration file for the site in question directly. The following is an cut down version to the configuration I use forhttp://www.swiftbyte.com. You will want to add the line starting try_file from the snippet bellow to your location entry.

location / {
    root /var/www/vhosts/yourdomain.com/httpdocs;
    try_files $uri $uri/ @extensionless-php;
    index index.php index.html;
}

Next add the following lines to your configuration file.

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

Once done reload Nginx and you should be all set to handle requests without the .php extension.

評論2