How to use Apache Mod_rewrite to remove php extension, while preserving the GET parameters?

前端 未结 2 829
自闭症患者
自闭症患者 2021-01-03 03:42

I was trying to remove the PHP extensions from my website. When user requests a PHP file, the PHP will be removed and the user will be redirected, and when the user types in

相关标签:
2条回答
  • 2021-01-03 03:57

    Thank you SteAp for your answer. I happened to be able to figure out a way to deal with it just now, and would like to share here in case others run into similar problems.

    In my rules, I have

    # remove .php ONLY if requested directly
    RewriteCond %{THE_REQUEST} (\.php\sHTTP/1)
    RewriteRule ^(.+)\.php$ /$1 [R=301,L,QSA]
    

    To execute external redirect when user requests a PHP file. The RewriteCond here is to prevent redirect loops - ie, endless redirect due to improper internal rewrite and external redirect (removing php, then adding php, then remove again, ...)

    When there are parameters, the actual header comes as http://domain.com/file.php?.... HTTP/1.1 Something like this, so the pattern in the RewriteCond won't work since it didn't take parameters into account.

    To solve it, simply replace the above code with:

    # remove .php ONLY if requested directly
    RewriteCond %{THE_REQUEST} (\.php(.*)\sHTTP/1)
    RewriteRule ^(.+)\.php$ /$1 [R=301,L,QSA]
    

    By doing so, the parameters can be matched by the pattern, and now everything works.

    Hope this will help someone having similar problem (or is it just a noob like me? lol)

    0 讨论(0)
  • 2021-01-03 04:06

    You might wish to use the %{QUERY_STRING} parameter documented here.

    Useful reading here and here.

    0 讨论(0)
提交回复
热议问题