Is it better to handle friendly/clean/pretty URLs with mod_rewrite or a language like PHP?

前端 未结 5 827
挽巷
挽巷 2021-02-04 14:55

I\'m developing my first decent-sized PHP site, and I\'m a bit confused about what the \"right way\" (assuming there ever is such a thing) to handle clean/friendly/pretty URLs i

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 16:00

    Use option #2 - why? RewriteRules in .htaccess are powerful tool, but they're some kind of static. I mean you cannot easily manage then using PHP (or whatever you're going to use). Also .htaccess doesn't provide so much flexibility, but has some advantages (for example: it's a bit faster).

    Option #2 also need .htaccess as you noticed, but in most cases RewriteRule takes the following form:

    RewriteRule (.\*) index.php
    

    Where index.php is your front controller.

    The biggest advantage (IMO) of this soultion is that each route is described in PHP (or whatever you use) so accessing these routes, modifying them is much easier. Furthermore these routes can be used then not only for changing URL into set of variables, but also in opposite way - to create URL from set of variables.

    I think the following example (from Symfony framework) will explain what I am talking about:

    // apps/.../config/routing.yml - Describes routing rules
    post:
       url:          /read/:id/:slug
       params:       { module: blog, action: index }
       requirements: { id: \d+, slug: \w+ }
    
    // apps/.../modules/blog/templates/indexSuccess.php - template for index action
    
    //creates: My first blog post
    

    Now whenever you change your rounting.yml file and change /read/:id/:slug into /:slug_:id all your links in application will turn into /my-first-blog-post_123.html.

    Doing such and others things when you use option #2 is much easier.

提交回复
热议问题