我尝试将这个 htaccess 规则转换为 nginx:
阿帕奇
# Necessary to prevent problems when using a controller named "index" and having a root index.php
# more here: http://httpd.apache.org/docs/2.2/content-negotiation.html
Options -MultiViews
# Activates URL rewriting (like myproject.com/controller/action/1/2/3)
RewriteEngine On
# Disallows others to look directly into /public/ folder
Options -Indexes
# When using the script within a sub-folder, put this path here, like /mysubfolder/
# If your app is in the root of your web folder, then leave it commented out
RewriteBase /php-mvc/
# General rewrite rules
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
nginx
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
root /home/goggelz/www;
server_name localhost;
rewrite_log on;
location / {
index index.php;
}
location /php-mvc {
if (!-d $request_filename){
set $rule_0 1$rule_0;
}
if (!-f $request_filename){
set $rule_0 2$rule_0;
}
if (!-e $request_filename){
set $rule_0 3$rule_0;
}
if ($rule_0 = "321"){
rewrite^/(.+)$ /php-mvc/index.php?url=$1 last;
}
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
问题是,我只想在 /home/goggelz/www/php-mvc 文件夹中使用重写,还有另一个问题:当我尝试打开 localhost 时,index.php 文件正在下载,但当我尝试连接 127.0.0.1 时,index.php 会执行。我该如何解决这些问题?
答案1
这是使用 nginx 指令的版本try_files
。
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
root /home/goggelz/www;
server_name localhost;
rewrite_log on;
index index.php;
location /php-mvc {
try_files $uri $uri/ @mvcrewrite;
}
location @mvcrewrite {
rewrite ^ /php-mvc/index.php?url=$request_uri last;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}
这里,try_files
首先使用 来检查请求的 URI 是否以文件或目录的形式存在。如果存在,则发送。如果不存在,则将请求转发到 块@mvcrewrite
,在该块中重写请求以将 URI 传递给 index.php
这也可能解决打开本地主机的问题。