如何在Nginx中使用重写?

时间:2016-08-09 16:02:46

标签: apache .htaccess nginx

我在Apache2中使用.htaccess,效果很好。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9_]+)$ profile.php?username=$1

现在我使用nginx重写,在网站可用,我做这个配置

server {
listen 80;
server_name domain.com;
root /home/domain;
index index.html index.htm index.php;
location / {
    rewrite "^([A-Za-z0-9_]+)$" profile.php?username=$1 last;
}
location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}
location ~ /\.ht {
    deny all;
}
}

但它不起作用,它显示404 Not Found,你能帮我解决这个错误吗?感谢。

1 个答案:

答案 0 :(得分:0)

重写翻译存在问题。请在此代码中检查此更新的重写翻译。

server {
listen 80;
server_name domain.com;
root /home/domain;
index index.html index.htm index.php;
location / {
if (!-e $request_filename){
rewrite ^/([A-Za-z0-9_]+)$ /profile.php?username=$1;
}
}
location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}
location ~ /\.ht {
    deny all;
}
}