简体   繁体   中英

Apache mod_rewrite: return a specific file if no file/directory exists

I'm writing a CMS that uses JavaScript to load the content of a page from the database. But I don't want hashes # in my URLs.

When a path is requested /cms/post/123 , Apache should load the file /cms/index.html . But if there's already a file under the path, for example /cms/image.png , Apache should return the file. Another point is that when for example /cms/admin or /cms/admin/post/123 is requested the file /cms/admin.html should be returned. The directory of the CMS may be different.

You can try using these rules in an htaccess file in your /cms/ directory

Options -Multiviews
RewriteEngine On

# if file exists, serve the file
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# if request is for admin, load admin.html
RewriteRule ^admin/ admin.html [L]

# everything else gets routed to index.html
RewriteRule ^ index.html [L]

You can place this in any directory that the CMS is in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM