Using pseudo-static rules for ThinkPHP on Nginx server

Publish: 2015-04-08 | Modify: 2015-04-08

Recently, our company used the ThinkPHP framework for a project. It worked fine on an Apache server with pathinfo enabled. However, when we deployed it on an Nginx server, we encountered an issue because Nginx doesn't support pathinfo. We found two possible solutions online:

  1. Modify ThinkPHP to make it work on Nginx.
  2. Modify Nginx to support pathinfo.

Personally, I find both methods a bit complicated and there's no guarantee of success. Later, I found a simpler and faster solution. First, add a new rewrite rule:

location / { 
    if (!-e $request_filename) { 
        rewrite ^(.*)$ /index.php?s=$1 last; 
        break; 
    } 
}

Then, change the URL mode in the ThinkPHP configuration file to 2:

'URL_MODEL'=>2,

If you have multiple projects and want to deploy them in different directories, such as putting the backend project in the "Admin" directory, you need to add another rewrite rule in Nginx:

location /Admin/ { 
    if (!-e $request_filename) { 
        rewrite ^/Admin/(.*)$ /Admin/index.php?s=$1 last; 
        break; 
    } 
}

Finally, don't forget to change the URL mode for this project to 2 as well.

If you are using the AMH panel, here's how to do it. The same principles apply to the LNMP stack:

  1. In the AMRewrite module, you can manage all the rewrite rules and add new ones. We need to add a new rule, so copy and save the rules mentioned above. See the screenshot below.

  2. In the virtual host settings, select the newly added rewrite rule. Now you will see that ThinkPHP supports pseudo-static on the Nginx server. LNMP users may need to manually find and modify the configuration files.

Please note that the above instructions are for ThinkPHP and Nginx in the context of AMH panel. LNMP users may need to adapt the steps accordingly.


Comments