我正在尝试测试NGINX,并可能从Apache进行切换。我读过nginx的速度要快得多,但我想成为它的评判者。我在获取NGINX的配置以匹配Apache设置时遇到了问题——主要是重写规则。我将解释我的应用程序是如何工作的,以及我希望能够在NGINX中做什么。
目前,我的应用程序正在处理发送到服务器的所有REQUEST_URI。即使URI不存在,我的应用程序也会处理该URI的处理。我之所以能够做到这一点,是因为Apache有一条重写规则。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?_url=$1 [QSA,NC]
</IfModule>
正如你所看到的,如果文件或目录实际上不存在,它会被发送到index.php。我甚至不检查查询字符串,我只是通过php变量$_SERVER['REQUEST_URI']处理URI本身,该变量在NGINX内部设置为fastcgi_param REQUEST_URI$REQUEST_URI;。我想用NGINX完成这件事,但我在这方面取得了一定的成功。
因此,基本上,如果domain.com/register.php存在,那么它将转到该url,如果不存在,它将被重定向到domain.com/index.php,应用程序将从那里处理URI。
这是我的服务器配置文件。这包含在nginx.conf文件的底部
server {
listen ####:80;
server_name ####;
charset utf-8;
access_log /var/www/#####/logs/access-nginx.log;
error_log /var/www/#####/logs/error-nginx.log;
root /var/www/######/public/;
location / {
index index.php index.html;
include /etc/nginx/mime.types;
try_files $uri /index.php?_url=$1;
include /etc/nginx/fastcgi.conf;
fastcgi_split_path_info ^(.+'.php)(/.+)$;
fastcgi_index index.php;
fastcgi_pass unix:/var/run/php-fpm.socket;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
rewrite_log on;
}
}
所以这种方法是有效的。我的意思是try_files$uri/index.php_url=$1指令正在按照我希望的方式处理URI,但MIME类型似乎不起作用。所有内容都被处理为text/html。这意味着我的.css和.js文件必须转换为一个.php文件并附加一个头,才能正确处理它。图像和字体文件似乎运行正常,但Chrome仍然将mime类型显示为html。我有mime.types文件,所以我不明白它为什么要这么做。我确实尝试过使用"rewrite"指令来处理try_files正在执行的操作,但并没有成功。
这是我在位置/块内尝试的重写:
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?_url=$1;
}
所以我的问题是:如何正确地重写不存在的文件和目录的uri,同时自动为文件提供正确的mime类型?
我最终解决了自己的问题。我在这里要做的是自己处理PHP文件,这肯定需要一段时间才能弄清楚。这是最后一个.conf文件,它发送正确的mime类型,并按照我需要的方式进行重写。希望这也能帮助其他人。
server {
listen #######:80;
server_name ######;
charset utf-8;
access_log /var/www/######/logs/access-nginx.log;
error_log /var/www/#######/logs/error-nginx.log;
root /var/www/#########/public/;
location ~ '.php$ {
include /etc/nginx/mime.types;
try_files $uri /index.php?_url=$1;
include /etc/nginx/fastcgi.conf;
fastcgi_split_path_info ^(.+'.php)(/.+)$;
fastcgi_index index.php;
fastcgi_pass unix:/var/run/php-fpm.socket;
}
location / {
index index.php index.html;
include /etc/nginx/mime.types;
try_files $uri /index.php?_url=$1;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
rewrite_log on;
}
}
使用location~.php$部分,使得只有php文件被发送到php-fpm。我还使用try_files指令来处理将所有不存在的URI发送到我的脚本,这正是我的应用程序所期望的。希望这能帮助到其他人!