mod_rewrite with name replacing ID

ε祈祈猫儿з 提交于 2020-03-05 09:46:34

问题


I have a page on my website that dynamically displays content. The URL structure is mywebsite.com/giveaway/giveaway.php?id=(any number) I wish to change that dynamic URL into a static/friendly URL mywebsite.com/giveaway/name-of-giveaway-corresponding-to-id. In my .htaccess file found in my root folder i have the following:

    RewriteEngine On

    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+\?page=([^\s&]+) [NC]
    RewriteRule ^ /page/%1? [R=301,L]

    # existing rule
    RewriteRule ^page/([^/]+)/?$ /?page=$1 [L,QSA]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [L]

The current .htaccess file removes .php and also redirects and changes a URL on my site from
mywebsite.com?page=number to mywebsite.com/page/number

I know you have to get the name corresponding to the ID in php from my database and use that, but im not sure how to write the code in the .htaccess file or how to use and pass the results from the database. Thanks for any help!


回答1:


I don't know if that is what you mean, but you can't connect the rewrite engine, which is part of the underlying Apache server layer, to the database, which has to be accessed by php.

So you can't rewrite the "name-of-giveaway-corresponding-to-id" to the id directly, you need to rewrite it to something like giveaway.php?nameofgiveaway=(name of giveaway) and then search the database for that string.

Your way to go is to add a rewrite rule like

RewriteRule ^giveaway/([^/]+)$ giveaway.php?nameofgiveaway=$1 [L,QSA] 

(not tested, so forgive me if something is wrong) and search for $_GET['nameofgiveaway'].



来源:https://stackoverflow.com/questions/21203525/mod-rewrite-with-name-replacing-id

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