Home > Mobile >  How to redirect the page after rewrite the URL
How to redirect the page after rewrite the URL

Time:01-29

I have to rewrite the URL so I have used the below code in my htaccess which is working

RewriteRule ^products/part/pumps/?$ pumps.php [L,NC]

if someone tries to access the url link exmple.com/products/part/pumps/ then it's showing the pumps.php data.

Now my issue is if some try to access the page example.com/pumps.php then how can I redirect to this link exmple.com/products/part/pumps/

I have tried but getting a redirecting error

Redirect 301  /pumps.php /products/part/pumps/

I have many pages and i have to redirect them also. sharing two example here

RewriteRule ^power\.php$ /products/engine/power/ [R=301,L]
RewriteRule ^connecting\.php$ /products/connection/power/connecting/ [R=301,L]

CodePudding user response:

Use the following before your existing rewrite:

# External redirect
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^pumps\.php$ /products/part/pumps/ [R=301,L]

(But test first with a 302 redirect to avoid potential caching issues.)

By checking that the REDIRECT_STATUS environment variable is "empty" we can redirect only direct requests from the user and not the rewritten request by the later rewrite. After the request is successfully rewritten, REDIRECT_STATUS has the value 200 (as in 200 OK HTTP status).

The RewriteCond (condtion) directive must precede every RewriteRule directive that triggers an external redirect.

The Redirect directive (part of mod_alias, not mod_rewrite) is processed unconditionally and will end up redirecting the rewritten request, resulting in a redirect loop. You need to use mod_rewrite throughout.


Use the END flag instead of RewriteCond (requires Apache 2.4)

Alternatively, you can modify your existing rewrite to use the END flag (instead of L) to prevent a loop by the rewrite engine. The RewriteCond directive as mentioned above can then be omitted. But note that the END flag is only available on Apache 2.4 .

For example:

# External redirects
RewriteRule ^pumps\.php$ /products/part/pumps/ [R=301,L]

# Internal rewrites
RewriteRule ^products/part/pumps/?$ pumps.php [END,NC]

It is advisable to group all the external redirects together, before the internal rewrites.

Unfortunately, due to the varying nature of these rewrites it doesn't look like the rules can be reduced further.

  • Related