Apache rewrite help

by 5 replies
7
I always struggle with this. Could someone save me an hour on Google and help me do this?

I want to redirect:

sitename.com/article-nn (where nn is any number of any length preceded by a dash.)

to:

sitename.com/articles/articles.php?aid=nn (where nn is the same number as above.

Example:

sitename.com/article-1040

redirects to:

sitename.com/articles/article.php?aid=1040

Thanks!
#programming #apache #rewrite
  • ----------------- .htaccess Begin below this line ---------------
    RewriteEngine On
    RewriteBase /

    ## Change RewriteBase to you path. Use / for root path

    #### Rewrite URL #######
    RewriteRule ^article-([0-9]+)$ article-$1/ [R]
    RewriteRule ^article-([0-9]+)/$ articles/articles.php?aid=$1 [L]

    ----------------- .htaccess End before this line ---------------
    PS. I manually wrote script without testing.
    • [ 1 ] Thanks
    • [1] reply
    • Thank you.

      Does the -([0-9]+) allow for a string of numbers of any length?

      0001 to 9999999999999, for example?
      • [1] reply
  • Banned
    [DELETED]
    • [ 1 ] Thanks
  • I'm not sure how much of the length limited.
    -([0-9]+) is allow only number 0, 1, 2, ..., 9
    • [1] reply
    • She's been talking about Google - but this just sends a 302 redirect:
      RewriteRule ^article-([0-9]+)$ article-$1/ [R]

      You should always use 301 redirect to redirect if it is a permanent change:
      RewriteRule ^article-([0-9]+)$ article-$1/ [R=301]

      You can find more information on that from Google here:
      301 redirects - Webmasters/Site owners Help
      • [ 1 ] Thanks

Next Topics on Trending Feed