Apache Mod Rewrite for Pretty URLs isn't working

后端 未结 4 529
你的背包
你的背包 2021-01-15 02:13

I\'m trying to figure out how to do an apache mod_rewrite to remap $_GET.

What I\'m trying to accomplish:

Currentl

4条回答
  •  青春惊慌失措
    2021-01-15 02:39

    Basically, you need two rules. One rule to redirect the client to a clean URL and another to internally rewrite the pretty URL to the real content via index.php.

    Assuming the index.php and .htaccess is in a directory cdi

    RewriteEngine on
    
    # prevent endless loop
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule ^ - [L]
    
    # redirect the client
    RewriteCond %{QUERY_STRING} URL=pages/(.+?)\.php
    RewriteRule ^index\.php$ /cdi/%1? [R,L]
    
    # exclude rewriting all files located in /cdi/files
    RewriteCond %{REQUEST_URI} !^/cdi/files/
    # rewrite to real content
    RewriteRule ^.*$ /cdi/index.php?URL=pages/$0.php [L]
    

    Update:

    When the request is /cdi/index.php?URL=pages/abc.php, the second rule extracts the needed URL part and redirects the client to the new URL path. The client then requests the new URL /cdi/abc and the third rule takes this and does an internal rewrite to the real content.

    This all works fine as it should, but would rewrite and redirect indefinitely. To break this endless rule, the first rule checks the environment %{ENV:...}, if the request was already redirected REDIRECT_STATUS and then stops the cycle with the RewriteRule

    RewriteRule ^ - [L]
    

    which matches everything ^ and does no substitution, but ends the rewrite cycle with the flag [L]

    Instead of using the system provided environment STATUS/REDIRECT_STATUS, you can also set a variable yourself with the flag E=SEO:1 for example, and then test for this variable with

    RewriteCond %{ENV:REDIRECT_SEO} 1
    

    For the REDIRECT_ prefix, see Available Variables.

提交回复
热议问题