使用nginx

时间:2016-05-04 22:00:00

标签: php nginx url-rewriting

我有一个使用php的网站。它是一个允许某人使用PHP GET调用搜索数据库的站点。然后它显示适合搜索的所有项目。

有许多搜索过滤器(价格,原始网站,类别)。在搜索用户输入“蓝色汽车”和“达拉斯”

之后,这就是网址的样子

http://example.com/after_search.php?search_title=blue+cars&search_location=Dallas&price-0=index&price_max=&price_min=&category=every-cat&store=all&max_number=20

有没有办法让它看起来像:

http://example.com/s/blue+cars/l/Dallas

不改变代码端的任何GET功能?

我还在网站上运行JQuery,如果这可以用来解决这个问题。

注意:我使用的是nginx

编辑1

鉴于以下建议,这似乎是一个nginx问题。

这是我当前的/ etc / nginx / sites-available / default文件:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    server_name server_domain_name_or_IP;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

当我在最后一个'}'之前添加它时:

# nginx configuration
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /array_search.php?path=$1 break;
}
}

这是nginx转换后的apache代码,它在下面的答案中,似乎没有任何变化。

我还将list(,$_GET['search_title'], $_GET['search_extra'], $_GET['search_location']) = explode('/',$_GET['path']); // Add more parameters as needed代码放在顶部的索引和after_search php文件中。

1 个答案:

答案 0 :(得分:3)

此答案假设您的网络服务器正在运行apache并且已启用mod_rewrite模块(通常默认情况下已启用)

这是我接近这个的一种方式。但是你必须在php文件的开头添加一些php代码(但你不必在现有实现中更改任何其他内容)

首先在与.htaccess相同的位置创建或修改after_search.php文件。将以下代码放在.htaccess文件中:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /after_search.php?path=$1 [NC,L,QSA]

这将使得网址http://example.com/s/blue+cars/l/Dallas将在幕后被重写为http://example.com/after_search.php?path=s/blue+cars/l/Dallas(意味着人们仍会看到http://example.com/s/blue+cars/l/Dallas

然后在你的php文件中,执行以下操作:

<?php
list(,$_GET['search_title'], $_GET['search_extra'], $_GET['search_location']) = explode('/',$_GET['path']); // Add more parameters as needed

这将拆分我们从htaccess文件创建的path参数,并将每个参数分配给$ _GET变量中的相应键。 你只需要在php文件的顶部执行一次这样的操作,就不必再触摸任何其他内容了。

编辑:我通过“htaccess转换为nginx转换器”运行apache配置,并获得了Nginx的以下代码

# nginx configuration
location / {
    if (!-e $request_filename){
        rewrite ^(.*)$ /after_search.php?path=$1 break;
    }
}