Is there any way to dynamically redirect URLs. For example, I want to redirect any URL from https://example.com/NNNNN to https://examplecom/?p=NNNNN.

Where NNNNN could be any possible numbers.

For example: https://example.com/1796 should redirect to https://example.com/?p=1796.


StackOverflow has already an answer for your question: https://stackoverflow.com/questions/2551553/htaccess-redirecting-dynamic-url

I guess that this should do the trick:

RewriteRule ^(\d+)$ /?p=$1 [R=302,L]
  • Thanks realloc, i tried this but didnt work for me. I tried below code. RewriteRule ^/(\d[^/]+) /?p=$1/ [R=302,L] – Avinash Patel Apr 1 '19 at 8:30
  • In .htaccess (directory context) you need to remove the slash prefix on the RewriteRule pattern. (The above directive - with a slash prefix - will never match.) This directive also needs to go near the top of the .htaccess file, before the WordPress front-controller (otherwise it will never get processed). If the source URL should only ever contain digits then include an end-of-string anchor $ on the pattern. – MrWhite Apr 1 '19 at 15:33
  • @MrWhite thanks but sorry to say i not very clear i can place the code on top of .htaccess but could you please confirm the code should like after amendment. Are you saying it should be like RewriteRule ^(\d[^/]+) ?p=$1/ [R=302,L] – Avinash Patel Apr 1 '19 at 16:02
  • 2
    Not quite... only remove the slash prefix on the RewriteRule pattern, not the substitution. You also added a slash to the end of the substitution - that's not in your initial example? For example: RewriteRule ^(\d[^/]+) /?p=$1 [R=302,L]. If the URL should only consist of digits then the regex should be more restrictive: RewriteRule ^(\d+)$ /?p=$1 [R=302,L] – MrWhite Apr 1 '19 at 16:10
  • 1
    I corrected the answer to reflect what @MrWhite wrote in the comments. Very interesting, thanks! – realloc Apr 2 '19 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.