如何使用.htaccess与nginx以及放置它的位置?

时间:2017-09-23 21:46:20

标签: apache .htaccess nginx ubuntu-14.04 url-rewrite-module

我是nginx的新手,我不知道如何在nginx中使用.htaccess以及将生成的代码放在nginx配置中的哪里。有没有人可以帮我转换为nginx?

这是我的.htaccess文件

 <IfModule mod_rewrite.c>

RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(admin)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]
RewriteCond %{QUERY_STRING} [^a-z](cast|char|convert|declare|delete|drop|exec|insert|meta|script|select|set|truncate|update)[^a-z] [NC]
RewriteRule (.*) - [F]
RewriteEngine On
# redirect with username
Options +FollowSymLinks
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(admin|assets|include)(.*)?$ /$1$2 [L,QSA,R=301]
RewriteRule ^user/([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^user/([a-zA-Z0-9_-]+)/$ user.php?username=$1
RewriteRule ^media/([a-zA-Z0-9_-]+)$ media.php?id=$1
RewriteRule ^media/([a-zA-Z0-9_-]+)/$ media.php?id=$1
RewriteRule ^tag/([^/.]+)$ tag.php?tag=$1 [QSA,L]
RewriteRule ^tag/([^/.]+)/$ tag.php?tag=$1 [QSA,L]
# turn on the mod_rewrite engine
RewriteCond %{REQUEST_FILENAME}.php -f
# IF the request filename with .php extension is a file which exists
RewriteCond %{REQUEST_URI} !/$
# AND the request is not for a directory
RewriteRule (.*) $1\.php [L]
# redirect to the php script with the requested filename



</IfModule>

请帮我转换为nginx,并指导我在哪里准确地输入此代码。谢谢!

1 个答案:

答案 0 :(得分:0)

Nginx不使用htaccess文件;您必须在Nginx站点配置中指定规则,例如/etc/nginx/sites-enabled/my-site.com.conf。您可以使用this之类的服务将现有的htaccess文件转换为Nginx conf,但转换后您必须重新检查是否有任何错误

下面是从上面的服务进行conf转换以了解所需的配置更改,但可能会有一些与您当前的nginx配置相关的更改。

location ~ \.(admin)$ { 
} 
location ~ /$ { 
} 
location / { 
 if ($query_string ~* "[^a-z](cast|char|convert|declare|delete|drop|exec|insert|meta|script|select|set|truncate|update)[^a-z]"){ 
  return 403; 
 } 
 if (!-e $request_filename){ 
       rewrite ^/(admin|assets|include)(.*)?$ /$1$2 redirect; 
  } 
  rewrite ^(.*)$ /$1\.php break; 
} 
location /user { 
    rewrite ^/user/([a-zA-Z0-9_-]+)$ /user.php?username=$1;
    rewrite ^/user/([a-zA-Z0-9_-]+)/$ /user.php?username=$1; 
} 
location /media { 
        rewrite ^/media/([a-zA-Z0-9_-]+)$ /media.php?id=$1; 
        rewrite ^/media/([a-zA-Z0-9_-]+)/$ /media.php?id=$1; 
 } 
 location /tag { 
     rewrite ^/tag/([^/.]+)$ /tag.php?tag=$1 break; 
     rewrite ^/tag/([^/.]+)/$ /tag.php?tag=$1 break; 
 }