Redirect Rules for WordPress to use as an API with Grunt
I thought this was awesome today. Thanks to this post I was able to set up a pretty neat working Grunt Angular project sitting inside a WordPress directory.
It's quite simple, really:
- All requests to the api, found at the url
/api/$(.*)
are served through a modifiedindex-api.php
, which is really just a dupe of the default WordPressindex.php
file. - Then, all requests to files (scripts, images) are made to be left in tact.
- Finally, all other requests are pushed through to my
site/dist/index.html
file, which is a resulting file of a grunt build. Pretty awesome to be able to use WordPress and a SPA app with a Grunt build process together.
My awesome .htaccess file for Wordpress with an API:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET"
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# Intercept any requests to assets, core, etc. here.. and keep them being written to the core (so they don't go to index.php)
RewriteRule ^scripts/(.*)$ /site/dist/scripts/$1 [NC,L]
RewriteRule ^images/(.*)$ /site/dist/images/$1 [NC,L]
RewriteRule ^api/(.*)$ index-api.php/$1 [NC,L]
# The magic, stops any requests to a file for being redirected.
# needed to be under the /core/ redirect
RewriteCond %{SCRIPT_FILENAME} !-f
# Rewrite all requests to my Grunt generated dist index.html
RewriteRule ^(.*) /site/dist/index.html [NC,L]
# Some requests (without trailing slashes) can fall through the above rule. This bit catches those stragglers.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ /$1/ [L,R=301]
</ifModule>
Written by Andrew Martin
Related protips
1 Response
DUDE THIS IS EXACTLY WHAT I AM LOOKING FOR!
However, I get a 500 error.
Where is your angular code sitting? On the top level of WordPress, or as a theme?
Which leads to the next question... how did you handle nonces?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Api
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#