PHP $_GET and .htaccess rewrite

半腔热情 提交于 2019-12-02 09:54:36

问题


I know this is probably a common question and has been asked before but .htacess looks foreign to me and I can't seem to get this to work from looking at previous questions.

I have a index script that searches and the syntax is:

.../listing/?field=property_type&query=retail

I simply want to rewrite this to:

.../listing/{field}/{query}

One other catch, I have some fields that are boolean.. for example:

.../listings/?forlease=1

So in this case I just use isset() but would like to rewrite this to:

.../listings/forlease/

Thanks for your help as always! Stack Overflow rocks!

EDIT:

I see some good answers but completely what I'm looking for:

User requests: .../listing/property_type/retail/

Apache rewrites to: ../listing/?field=property_type&query=retail

Script sees: $_GET['field']='property_type' & $GET['query']='retail'

In the case of the boolean (all booleans will have only one Dir):

User requests: .../listing/forlease/

Apache rewrites to: ../listing/?forlease=1

Script sees: $_GET['forlease'] = 1


回答1:


In your .htaccess you can have a couple of simple rules:

RewriteRule ^.*/listings/([a-zA-Z0-9_]+)/([a-zA-z0-9_]+)$ /listing/?property_type=$1&query=$2 [QSA,L]
RewriteRule ^.*/listings/forlease/$ /listing/?forlease=1 [QSA,L]



回答2:


If your webserver is Apache, then you can use mod_rewrite.

Check out : http://www.yourhtmlsource.com/sitemanagement/urlrewriting.html =)




回答3:


RewriteRule ^.*/listing/([^/]*)/?$ listing/?$1=1 [NC,L]
RewriteRule ^.*/listing/([^/]*)/?(.*)$ listing/?property_type=$1&query=$2 [NC,L]

Try this, first checks for a single condition (http://...listing/forlease), otherwise rewrites to (http://...listing/field/query)

You might want:

RewriteRule ^.*/listing/([^/]*)/?$ listing/?$1=1&%{QUERY_STRING} [NC,L]
RewriteRule ^.*/listing/([^/]*)/?(.*)$ listing/?property_type=$1&query=$2&%{QUERY_STRING} [NC,L]

To keep any additional parameters in the query string.



来源:https://stackoverflow.com/questions/4286769/php-get-and-htaccess-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!