Why rewrite ?
- To remove unneccessary “index.php” in url (e.g “www.123.com/app/inedx.php/hello” can be accessed using “www.123.com/app/hello”)
- Simplify url
- redirect site
- others
Environment
- vps
- lnmp
- ubuntu 11.10
- CodeIgniter (version 2.1-stable)
- web root /home/wwwroot/
- Nginx config file location /usr/local/nginx/conf/nginx.conf
Allow url like xx/index.php/home
Need to allow pathinfo(not safe) or edit config file
Edit /usr/local/nginx/conf/nginx.conf
Change
location ~ .*\.(php|php5)?$
{
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
}
To
location ~ \.php
{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
set $path_info "";
set $real_script_name $fastcgi_script_name;
if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
set $real_script_name $1;
set $path_info $2;
}
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
fastcgi_param SCRIPT_NAME $real_script_name;
fastcgi_param PATH_INFO $path_info;
}
And restart lnmp. Worked for me.
Remove index.php in url
Add the following to nginx.conf inside server{…}
location /app
{
index index.php;
# 重写到index
if ($request_filename !~ (js|css|images|robots/.txt|index/.php.*) ) {
rewrite ^/app/(.*)$ /app/index.php/$1 last;
#break;
}
}
So that _www.123.com/app/hello_ in the browser will be interpreted as _www.123.com/app/index.php/hello_
The code is not efficienty, needs improvement
Test your rewrite rule
Note the “last” flag in
rewrite ^/app/(.*)$ /app/index.php/$1 last;
Change to
rewrite ^/app/(.*)$ /app/index.php/$1 redirect;
The rewrite result would display in the web browser
Using .htaccess
You can write your rewrite rules directly in .htaccess file resides under your web folder. All you need to to is include that .htacess file in your nginx.conf file. For example:
location /app
{
index index.php;
# 重写到index
if ($request_filename !~ (js|css|images|robots/.txt|index/.php.*) ) {
include /home/CI/app/.htaccess;
#break;
}
}
And the content of .htaccess file would be:
rewrite ^/app/(.*)$ /app/index.php/$1 last;