Web Design Tutorials: Photoshop, HTML, Flash, PHP

PHP Tutorial – Using mod_rewrite to symfony backend

So, I am building a web application with symfony framework and I wanted to redirect traffic from /admin/ to my backend.php application. It was unbelievably simple yet I was unable to find very much help at the Symfony project forums.

I did get a few ideas from some pages regarding editing the routing.yml file but they were primarily about editing the routing.yml in the frontend application. Anyways, let me get on to what I did.

Now, you DO NOT have to edit anything in the /web folder except the .htaccess. Do not move the backend.php to an admin folder and rename it to index.php or anything similar. There was only 2 files you have to edit total.

routing.yml
  1. # http://www.symfony-project.org/reference/1_4/en/10-Routing
  2. # default rules
  3. homepage:
  4. url:   admin/
  5. param: { module: default, action: index }
  6. # generic rules
  7. # please, remove them by adding more specific rules
  8. default_index:
  9. url:   admin/:module
  10. param: { action: index }
  11. default:
  12. url:  admin/:module/:action/*

Under “homepage”, “default_index” and “default”, you will will want to edit the url option like I did above. Adding “admin” before the forward slash. Just like any other symfony application, edit the param: module option to whatever module you want your backend app to go to by default.

.htaccess
  1. Options +FollowSymLinks +ExecCGI
  2. RewriteEngine On
  3. # uncomment the following line, if you are having trouble
  4. # getting no_script_name to work
  5. #RewriteBase /
  6. # we skip all files with .something
  7. #RewriteCond %{REQUEST_URI} ..+$
  8. #RewriteCond %{REQUEST_URI} !.html$
  9. #RewriteRule .* - [L]
  10. # we check if the .html version is here (caching)
  11. RewriteRule ^$ index.html [QSA]
  12. RewriteRule ^([^.]+)$ $1.html [QSA]
  13. RewriteCond %{REQUEST_FILENAME} !-f
  14. # catch requests for our backend controller
  15. RewriteRule ^admin(.*)$ backend.php [QSA,L]
  16. # do this again for our frontend controller
  17. RewriteCond %{REQUEST_FILENAME} !-f
  18. # no, so we redirect to our front web controller
  19. RewriteRule ^(.*)$ index.php [QSA,L]

The only thing I added here was the actual RewriteRule that catches requests for /admin and rewrites it to backend.php. The key was the additional

  1. RewriteCond ${REQUEST_FILENAME} !-f

right before the original rewrite to the frontend controller. I say this was the key because I had the RewriteRule there before but it was not working properly until I added the RewriteCond.

  1. ./syfmony cc

Clear your symfony cache and now if you go to http://yourdomain.com you will go to your frontend app and http://yourdomain.com/admin will go to your backend app.

Enjoy and thank you for reading.

you may also like:

Leave a Reply

Powered by WordPress | Designed by Elegant Themes