Apache到Nginx的转换(新手)

我有一个PHP的Nginx Web服务器设置,我想在Nginx上移动,我想将这些.htaccess规则转换为nginx.conf文件:

RewriteRule ^blog(|/)$ /data/core/site/blog.php RewriteRule ^blog/post(|/)$ /data/core/site/blogpost.php 

到目前为止,这是我的:

 location /blog { rewrite ^(.*)$ /data/core/blog.php last; } 

但是,如果我访问该页面( http://example.com/blog ),它给我的文件下载,我想它服务器的PHP和显示内容,我将如何解决这个问题?

完整的Nginxconfiguration:(在Windows上使用Winginx软件包):

 server { listen 127.0.0.1:80; server_name localhost; root home/localhost/public_html; index index.php; log_not_found off; #access_log logs/localhost-access.log; charset utf-8; location ~ /\. { deny all; } location = /favicon.ico { } location = /robots.txt { } location ~ \.php$ { fastcgi_pass 127.0.0.1:9054; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; include fastcgi_params; } location /blog { rewrite ^(.*)$ /data/core/blog.php last; } } 

请求处理

要记住的基本规则是: nginx提供一个位置的请求 (您可以强调更多: 和一个位置 )。

阅读: http : //nginx.org/en/docs/http/request_processing.html

location匹配

阅读: location文件

根据你的configuration,nginx将首先在/blog 前缀位置匹配,然后在\.php$ regex位置匹配,并且最终将服务于后者。 使用您提供的configuration,脚本不应再作为原始文件下载,而应该发送到PHP。

但是,这并不意味着您的configuration是正确的:请求不是由您的/blog位置提供的,而此位置目前无用。

  1. 避免使用正则expression式位置来过滤请求是一种很好的做法,这些位置是基于命令的,这是不好的(记住Apache命令的命令灵敏度噩梦?)。 要过滤,请使用基于最长匹配的前缀位置。 如果你最终需要一个正则expression式,你可以embedded位置。
  2. 为什么不直接把你的fastcgi*指令放到/blog位置? 然后,可以使用fastcgi_param SCRIPT_FILENAME $document_root/data/core/blog.php来代替使用$fastcgi_script_namevariables(从location匹配中猜测)。 顺便说一下, $fastcgi_script_filename已经包含了开始/ ,不需要在variables之间加一个
  3. 如果可以避免使用redirect,请避免使用redirect。 避免特别rewrite更多。 简单的用户redirect(使用HTTP状态码发送给客户端的redirect通知完成的URL重写)可以通过return来完成。 你在这里做的是一个内部redirect(在服务器本地完成):它唯一的用途是改变用于SCRIPT_FILENAME参数的URI。

你可以使用初学者:

 location /blog { fastcgi_pass 127.0.0.1:9054; fastcgi_param SCRIPT_FILENAME $document_root/data/core/blog.php; include fastcgi_params; # Useless here since SCRIPT_FILENAME will never be a directory indeed fastcgi_index index.php; location /blog/post { fastcgi_pass 127.0.0.1:9054; fastcgi_param SCRIPT_FILENAME $document_root/data/core/blogpost.php; include fastcgi_params; } } 

这是对我的问题的解决办法,在对问题进行了大量的研究后,我发现它非常简单:

 server { listen 127.0.0.1:80; server_name virjox www.virjox; root home/virjox/public_html; index index.php; log_not_found off; #access_log logs/virjox-access.log; charset utf-8; sendfile on; location ~ /\. { deny all; } location = /favicon.ico { } location = /robots.txt { } location ~ \.php$ { fastcgi_pass 127.0.0.1:9054; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; include fastcgi_params; rewrite ^/(.*)\.html /$1\.php; } location /blog { rewrite ^/blog(|/)$ /data/core/blog.php; } } 

这完美的作品。