Last Updated: February 25, 2016
· andrewmartin

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:

  1. All requests to the api, found at the url /api/$(.*) are served through a modified index-api.php, which is really just a dupe of the default WordPress index.php file.
  2. Then, all requests to files (scripts, images) are made to be left in tact.
  3. 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]


1 Response
Add your response


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 ·