Jedabero
Jedabero

Reputation: 35

Configure .htacces for public folder

I have the following folder structure in a php project: project/ |--app/ |--public/ |--img/ |--.htaccess |--index.php |--vendor/ How would the .htacces file be in order to serve the public folder from host.domain/project/ ?

I'm guessing the .htaccess would need to be in the root folder. I could also edit the servers virtual host file for host.domain but I don't know how would the configuration be.

Upvotes: 0

Views: 4205

Answers (2)

William Desportes
William Desportes

Reputation: 1711

Here is how to mix a public folder system with an old one

The website is like

  • / -> /public/index.php?route=/
  • /mypage -> /public/index.php?route=/mypage
  • /fakefolder/mypage -> /public/index.php?route=/fakefolder/mypage
  • /fakefolder/mypage?a=b&foo=bar -> /public/index.php?route=/fakefolder/mypage&a=b&foo=bar (this works because of QSA flag of Apache2)

All static files present in /public/ are accessible, for example /assets/img/foo.png is at /public/assets/img/foo.png on file system

And the admin system works the "old way"

  • /admin/ -> /admin/index.php
  • /admin/login -> /admin/login.php
RewriteEngine on

# Already in admin folder, use admin folder, old routing system
RewriteCond %{REQUEST_URI} ^/admin
# It is a folder, do not re-write it
RewriteCond %{REQUEST_FILENAME} !-d
# Do not hit this once more if it already is a file, .php was already added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^admin/(.*)$ /admin/$1.php [L,QSA]

# See: https://stackoverflow.com/a/43957084/5155484
# Not already in public folder or admin folder, use public folder
RewriteCond %{REQUEST_URI} !^/public
RewriteCond %{REQUEST_URI} !^/admin
RewriteRule ^(.*)$ /public/$1 [L]


# Use router if it was redirected by previous pass to public folder
# And it is not a file, that way files are served as static files
RewriteCond %{REQUEST_URI} ^/public
# Do not hit this once more if it already is a file, .php was already added
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^public/(.*)$ /public/index.php?route=/$1 [L,QSA]

If you change / to ./ for the RewriteRule on some production servers you will have an error 500.

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74128

If you have access to the main/virtual host configuration, you can set the DocumentRoot to the public folder

DocumentRoot /path/to/project/public

If you cannot do that, or want to use mod_rewrite and project is the document root, you can do a rewrite to public

RewriteCond %{REQUEST_URI} !^/public
RewriteRule ^(.*)$ /public/$1 [L]

Upvotes: 0

Related Questions