MQTT supports the topic rewrite function. According to user-configured rewrite rules, the original topic is rewritten to a new target topic when the client subscribes or publishes.
In certain scenarios, modifying business topics can be very difficult. In such cases, the topic rewrite function can be used. By setting topic rewrite rules, the original topic is rewritten to a new target topic when the client subscribes or publishes.
After topic rewrite is enabled, MQTT uses the topic in the packet to sequentially match the original topics in the rewrite rules. After a successful match, the regular expression extracts information from the original topic, then replaces it with the target expression to generate a new topic.
- MQTT executes topic rewrite according to the configuration order of the rewrite rules. When a topic matches the original topics of multiple rewrite rules at the same time, only the first matching rule is used to rewrite the topic.
- If the regular expression in the rule does not match the topic in the MQTT packet, the rewrite fails, and other rules will not be used for rewriting.
- In the Dashboard navigation bar, select Management > MQTT Advanced Features > Topic Rewrite.
- Click Add in the upper right corner of the page.
- In the pop-up dialog box, configure the parameters for the topic rewrite rule, then click Add.
- Edit and delete operations are supported; please perform them as needed.
Suppose you have configured multiple topic rewrite rules as follows:
Rule ①
- Original topic: test/+/topic/#
- Regular expression: ^test/(.+)/topic/(.+)$
- Target topic: test/topic/$2
Rule ②
- Original topic: doc/test/+
- Regular expression: ^doc/test/(\d+)$
- Target topic: mqtt/test/$1
If the topics you subscribe to on the client are test/1, test/mqtt/topic/1, and doc/test/1, the actual subscription topic descriptions are as follows:
- The test/1 topic does not match the original topic of any rewrite rule, so no topic rewrite rule is executed. The actual subscription topic is test/1.
- test/mqtt/topic/1 topic matches the original topic in rule ①. MQTT executes the topic rewriting rule, matches elements [mqtt, 1] using a regular expression, substitutes the second matched element into the target topic test/topic/$2, so the final actual subscribed topic is test/topic/1.
- doc/test/1 topic matches the original topic in rule ②. The topic rewriting rule is executed, and after regular expression replacement, the final actual subscribed topic is mqtt/test/1.